簡體   English   中英

使用PHP即時創建XML

[英]XML creation on the fly using PHP

我對在運行時創建XML文件的需求很小。 對我來說,創建一個普通的xml文件是沒有問題的,它看起來像這樣:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <item>
    <name></name>
  </item>
</root>

但是我的要求是,我需要創建一個XML文件,其輸出為:

<?xml version="1.0" encoding="UTF-8"?>
    <root>
      <item>
        <name url = "C:\htdocs\proj1\source_file1"/>
        <name url = "C:\htdocs\proj1\source_file2"/>
        <name url = "C:\htdocs\proj1\source_file3"/>
      </item>
    </root>

我已經嘗試過這種方式:

<?php   
  $domtree = new DOMDocument('1.0', 'UTF-8');
  $domtree->formatOutput = true;  

  $xmlRoot = $domtree->createElement("root");  
  $xmlRoot = $domtree->appendChild($xmlRoot);

  $item = $domtree->createElement("item");
  $item = $xmlRoot->appendChild($item);

  $name= $domtree->createElement("name");
  $name = $item->appendChild($name);

  $sav_xml = $domtree->saveXML();
  $handle = fopen("new.xml", "w");
  fwrite($handle, $sav_xml);
  fclose($handle);     
?>

但是我想將url =“ path”追加/添加到我的元素中。 我曾嘗試用url和path聲明變量,但這會引發如下錯誤:

 Uncaught exception 'DOMException' with message 'Invalid Character Error'

任何想法如何解決這個問題!

謝謝

您只需要通過php DOM聲明該屬性:

...
$name= $domtree->createElement("name");

$urlAttribute = $domtree->createAttribute('url');
$urlAttribute->value = 'C:\htdocs\proj1\source_file1';
$name->appendChild($urlAttribute);

$item->appendChild($name);
...

鏈接到DOMDocument文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM