Search code examples
xmldomdocumentphp-7.3

DOMDocument - merge elements into one XML


Trying to merge root and body into one XML. The reason the 2 elements are splitted when being created is because they will be pre-constructed and exist in different files, thus loaded.

My code:

<?php


$root = new DOMDocument();
$root->loadXML('<root/>');

$body = new DOMDocument();
$body->loadXML('<body/>');

foreach ($body->documentElement->childNodes as $child) {
  $body->documentElement->appendChild(
    $body->importNode($child, TRUE)
  );
}

echo $body->saveXML();

Wanted result:

<?xml version="1.0"?>
<root>
<body/>
</root>

Solution

  • The length of $body->documentElement->childNodes->length is 0 as there are no childNodes for <body/>

    As you want to import $body into $root you should append the child and import the node using root instead of child.

    For example

    $root = new DOMDocument();
    $root->loadXML('<root/>');
    
    $body = new DOMDocument();
    $body->loadXML('<body/>');
    
    foreach ($body->childNodes as $child) {
        $root->documentElement->appendChild(
            $root->importNode($child, TRUE)
        );
    }
    
    echo $root->saveXML();
    

    Output

    <?xml version="1.0"?>
    <root><body/></root>
    

    Php demo