0

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

2

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.