简体   繁体   English

使用PHP即时创建XML

[英]XML creation on the fly using PHP

I have a small requirement where I need to create a XML file on the fly. 我对在运行时创建XML文件的需求很小。 It was no problem for me to create a normal xml file which would be looking like this: 对我来说,创建一个普通的xml文件是没有问题的,它看起来像这样:

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

But my requirement is such that I need to create a XML file whose output is: 但是我的要求是,我需要创建一个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>

I have tried in this fashion: 我已经尝试过这种方式:

<?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);     
?>

But I wanted to append/add the url="path" to my elements. 但是我想将url =“ path”追加/添加到我的元素中。 I have tried declaring variables with url and path but this throws me errors like: 我曾尝试用url和path声明变量,但这会引发如下错误:

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

Any ideas how to approach this problem! 任何想法如何解决这个问题!

Thanks 谢谢

You just have to declare that attributes via php DOM: 您只需要通过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 链接到DOMDocument文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM