This is a discussion on php5 and xml within the PHP Language forums, part of the PHP Programming Forums category; I am trying to find a way to add a child node at the top of the node tree. My ...
|
|||||||
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|||
|
Andrew M. wrote:
> I am trying to find a way to add a child node at the top of the node > tree. My xml document has root <songs> and child elements <song>. I > need to be able to insert <song> elements at the top not at the > bottom like appendChild. > Use insertBefore, examples: <?php $xml = new DomDocument(); // Create and append the root node $root = $xml->createElement("root"); $xml->appendChild($root); // Create and add the first child $child = $xml->createElement("song"); $child->setAttribute("number", 1); $firstChild = $root->appendChild($child); // Create and add another child $child = $xml->createElement("song"); $child->setAttribute("number", 2); $root->insertBefore($child, $firstChild); ?> *Or* <?php $xml = new DomDocument(); // Create and append the root node $root = $xml->createElement("root"); $xml->appendChild($root); // Create and add the first child $child = $xml->createElement("song"); $child->setAttribute("number", 1); $root->appendChild($child); // Create and add another child $child = $xml->createElement("song"); $child->setAttribute("number", 2); // Find the first song child element $firstChild = $root->getElementsByTagName("song")->item(1); $root->insertBefore($child, $firstChild); ?> JW |
|
|||
|
Janwillem Borleffs wrote:
> // Find the first song child element > $firstChild = $root->getElementsByTagName("song")->item(1); > This example is incorrect, you should get the first item: $firstChild = $root->getElementsByTagName("song")->item(0); JW |
|
|||
|
Thank you very much Janwillem. That did the trick . I had a feeling it
was insertBefore but I was having a lot of trouble tracking down documentation about how to use it. Janwillem Borleffs wrote: > Janwillem Borleffs wrote: > >>// Find the first song child element >>$firstChild = $root->getElementsByTagName("song")->item(1); >> > > > This example is incorrect, you should get the first item: > > $firstChild = $root->getElementsByTagName("song")->item(0); > > > JW > > > |