Search code examples
phpxmlsimplexml

append XML tree as child to another XML, using PHP


I want to add an XML tree into another XML, and I have tried with following code which is not working:

<?php
$str1 = '<parent>
            <name>mrs smith</name>
         </parent>';

$xml1 = simplexml_load_string($str1);
print_r($xml1);

$str2 = '<tag>
             <child>child1</child>
             <age>3</age>
         </tag>';
$xml2 = simplexml_load_string($str2);
print_r($xml2);

$xml1->addChild($xml2);
print_r($xml1);
?>

Expect output XML:

<parent>
    <name>mrs smith</name>
    <tag>
    <child>child1</child>
    <age>3</age>
    </tag>
</parent>

Please assist me.


Solution

  • You can use DOMDocument::importNode

    <?php 
    
    $str2 = '<tag>
                 <child>child1</child>
                 <age>3</age>
             </tag>';
    
    $str1 = '<parent>
                <name>mrs smith</name>
             </parent>';
    
    $tagDoc = new DOMDocument;
    $tagDoc->loadXML($str2);
    
    $tagNode = $tagDoc->getElementsByTagName("tag")->item(0);
    //echo $tagDoc->saveXML();
    
    $newdoc = new DOMDocument;
    $newdoc->loadXML($str1);
    
    $node = $newdoc->importNode($tagNode, true);
    $newdoc->documentElement->appendChild($node);
    
    echo $newdoc->saveXML();die;