User Tools

Site Tools


php:addchildxml

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

php:addchildxml [2013/03/16 17:40] (current)
Line 1: Line 1:
 +====  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:
 +
 +<code xml>
 +<?xml version="​1.0"​ encoding="​UTF-8"?>​
 +<​preferences>​
 +  <user name="​admin">​
 +    <setting key="​background">#​000000</​setting>​
 +  </​user>​
 +</​preferences>​
 +</​code>​
 +
 +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).
 +
 +<code php>
 +    $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);​
 +</​code>​
 +
 +
 +After that we'll have:
 +
 +<code xml>
 +<?xml version="​1.0"​ encoding="​UTF-8"?>​
 +<​preferences>​
 +  <user name="​admin">​
 +    <setting key="​background">#​000000</​setting>​
 +    <setting key="​color">#​11ff11</​setting>​
 +  </​user>​
 +</​preferences>​
 +</​code>​
php/addchildxml.txt ยท Last modified: 2013/03/16 17:40 (external edit)