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