title: both appendChild and insertBefore when called on DOMDocument append node after root
body: <p>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)</p>
  
  <pre><code>function addUser($tag, $hash)
      {
          $dom = new DOMDocuemnt();
          $dom-&gt;preserveWhiteSpace = false;
          $dom-&gt;formatOutput = true;
          $dom-&gt;load('file');
  
          $parent = $dom-&gt;createElement($tag);
          foreach($hash as $elm =&gt; $value){
              $n = $dom-&gt;createElement($elm, $value);
              $parent-&gt;appendChild($n);
          }
          $dom-&gt;appendChild($parent);
  
          $dom-&gt;save('file');
          return $dom-&gt;saveXML();
      }
  </code></pre>
  
  <p>Only problem is <code>$dom-&gt;appendChild($parent)</code> appends everything after the root element's closing tag, mucking up my xml file. So I tried <code>$dom-&gt;insertBefore($parent)</code> with the same result. So instead I tried <code>$xpath = new DOMXPath($dom); $root = $xpath-&gt;query('/')-&gt;item(0); $root-&gt;appendChild($parent);</code>. Same result. Then I tried selecting the root element with <code>$dom-&gt;getElementsByTagName(name of root)-&gt;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?</p>