Search code examples
phpxmldomdocumentappendchild

PHP DOMDocument appendChild to end of root


I've got an XML formatted like so

<things>
  <thing>
    <name>foo</name>
    <id>1</id>
  </thing>
  <thing>
    <name>bar</name>
    <id>2</id>
  </thing>
</things>

And I've created a new <thing> element with info from a form. When I do $dom->appendChild($newthing), it's appended to the end of the document, after </things>. Like this

   <things>
     <thing>
        <name>foo</name>
        <id>1</id>
      </thing>
      <thing>
        <name>bar</name>
        <id>2</id>
      </thing>
    </things>
    <thing>
       <name>bar</name>
       <id>2</id>
    </thing>

Obviously I want my new element to be a child of the root element, not after it. How do I do that?


Solution

  • $dom->documentElement->appendChild($newthing);
    

    From the PHP manual:

    documentElement
    This is a convenience attribute that allows direct access to the child node that is the document element of the document.