1

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.

4
  • 1
    Have you read the manual for the addChild() method? It doesn't accept a SimpleXMLEmlement object as argument. Commented Jan 19, 2017 at 6:51
  • Thanks @Magnus Eriksson what can be done instead?please suggest Commented Jan 19, 2017 at 7:02
  • You could use the method as it's intended? :) Where does the data come from to start with? Commented Jan 19, 2017 at 7:03
  • 1
    You can use DOM for that. In DOM you can import nodes from another document and append them. Commented Jan 19, 2017 at 9:32

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.