both appendChild and insertBefore when called on DOMDocument append node after root

DraipiptSpith

New Member
I have a function to add a valueless element and a bunch of child elements with values to an xml file, so I wrote it to take two arguments $tag(String the parent node) and $hash(Array $elm=>$elm_value)\[code\]function addUser($tag, $hash) { $dom = new DOMDocuemnt(); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $dom->load('file'); $parent = $dom->createElement($tag); foreach($hash as $elm => $value){ $n = $dom->createElement($elm, $value); $parent->appendChild($n); } $dom->appendChild($parent); $dom->save('file'); return $dom->saveXML(); }\[/code\]Only problem is \[code\]$dom->appendChild($parent)\[/code\] appends everything after the root element's closing tag, mucking up my xml file. So I tried \[code\]$dom->insertBefore($parent)\[/code\] with the same result. So instead I tried \[code\]$xpath = new DOMXPath($dom); $root = $xpath->query('/')->item(0); $root->appendChild($parent);\[/code\]. Same result. Then I tried selecting the root element with \[code\]$dom->getElementsByTagName(name of root)->item(0);\[/code\] And was surprised when that actually worked! But what if I don't know the tag name? Is there another way to select the root element so that calling appendChild or inserBefore will add the element before the root closing tag instead of after it?
 
Back
Top