使用PHP即时创建XML

时间:2011-12-08 12:40:11

标签: php xml

我有一个小要求,我需要动态创建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'

任何想法如何解决这个问题!

由于

1 个答案:

答案 0 :(得分:3)

您只需通过php DOM声明该属性:

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

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

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

Link to DOMDocument docs