简体   繁体   中英

XML creation on the fly using PHP

I have a small requirement where I need to create a XML file on the fly. It was no problem for me to create a normal xml file which would be looking like this:

<?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 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. I have tried declaring variables with url and path but this throws me errors like:

 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:

...
$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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