tendaitakas
tendaitakas

Reputation: 358

PHP DOM appendeing children elements to root

I am trying to append children elements to a pre-loaded root element like below

    $document = new DOMDocument('1.0', 'UTF-8');
    $document->loadXML('<books></books>');


    $content = '<books>
                   <book>
                       <athors>
                           <athor>
                               <name>John Doe</name>
                           </athor>
                       </athors>
                   </book>
               </books>';
     
    $books = new DOMDocument()

    $books->loadXML($content);

    foreach ($books as $book){
        $document->appendChild($document->importNode( $book, true ));
    }

For some reason, the result xml document will be like below, with the closing tag of the root element at the beginning of the document:

   <?xml version="1.0"?>
   <books/>
         <book>
                       <athors>
                           <athor>
                               <name>John Doe</name>
                           </athor>
                       </athors>
          </book>

I want it to be like below:

   <?xml version="1.0"?>
   <books>
         <book>
                       <athors>
                           <athor>
                               <name>John Doe</name>
                           </athor>
                       </athors>
          </book>
   <books/>

Upvotes: 1

Views: 72

Answers (1)

Barmar
Barmar

Reputation: 780818

You're iterating over the children of the root element in $books, not the book elements. And then you're appending to the root of $document, not the books element.

You need to drill down in each to get to the appropriate nodes.

<?php
$document = new DOMDocument('1.0', 'UTF-8');
$document->loadXML('<books></books>');
$documentBooks = $document->childNodes[0];

$content = '<books>
                   <book>
                       <athors>
                           <athor>
                               <name>John Doe</name>
                           </athor>
                       </athors>
                   </book>
               </books>';
     
$books = new DOMDocument();
$books->loadXML($content);
$bookItems = $books->childNodes[0]->childNodes;

foreach ($bookItems as $book){
    $documentBooks->appendChild($document->importNode( $book, true ));
}
echo $document->saveXML();

Upvotes: 2

Related Questions