使用PHP将XML树作为子树附加到另一个XML

时间:2017-01-19 06:39:54

标签: php xml simplexml-load-string

我想将XML树添加到另一个XML中,我尝试使用以下不起作用的代码:

<?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);
?>

期望输出XML:

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

请帮助我。

1 个答案:

答案 0 :(得分:1)

您可以使用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;