User Tools

Site Tools


php:addchildxml

DOM & XML - HOW TO ADD A CHILD NODE INSIDE AN EXISTING XML STRUCTURE

23/06/2008

You might encounter this issue but on the internet you'll find very little indications how to actually do it. So here it goes…

We suppose that we already have an xml file with the following content:

<?xml version="1.0" encoding="UTF-8"?>
<preferences>
  <user name="admin">
    <setting key="background">#000000</setting>
  </user>
</preferences>

Under node with the name “admin” we store different settings in nodes called 'setting'. What we want is to add a new setting node after the first one (note that we have only one so this will be also the last one).

    $dom = new DOMDocument();
    // this should stay before load() to format output otherwise it doesn't
    $dom->preserveWhiteSpace = false;
    $dom->load($file);
    $dom->formatOutput = TRUE;
 
    // Find out the nodes list called user; in our file should be only one!
    $usernodes = $dom->getElementsByTagName("user");
 
    foreach ($usernodes as $node) {
        $newelem = $dom->createElement("setting", "#11ff11");
        $newelem->setAttribute("key", "color");
        $node->appendChild($newelem);
    }
 
    //echo $dom->saveXML();
    $dom->save($file);

After that we'll have:

<?xml version="1.0" encoding="UTF-8"?>
<preferences>
  <user name="admin">
    <setting key="background">#000000</setting>
    <setting key="color">#11ff11</setting>
  </user>
</preferences>

php/addchildxml.txt · Last modified: 2013/03/16 17:40 (external edit)