You can do it using DOMDocument:
<?php
$aDoc = DOMDocument::loadXML('<?xml version="1.0" encoding="UTF-8" ?>
<first_root>
<element1/>
<element2>
<embedded_element/>
</element2>
</first_root>');
$bDoc = DOMDocument::loadXML('<?xml version="1.0" encoding="UTF-8" ?>
<foo>
<bar/>
</foo>');
$aEmbeddedElement = $aDoc->getElementsByTagName('embedded_element')->item(0);
$bFoo = $bDoc->documentElement;
$aImportedFoo = $aDoc->importNode($bFoo,true);
$aEmbeddedElement->insertBefore($aImportedFoo);
echo $aDoc->saveXML();
?>
Here I imported the XML into DOMDocument
s, then I picked up the first embedded_element
occurrence and foo
node. After you have to import deeply foo
into the first document. Now you can insert foo
before embedded_element
.
Obviously this is only the happy case...
Documentation: DOM
With SimpleXML
you can accomplish this by building a third document based on the first two because you can't append SimpleXMLElements into others. (Or maybe you can but there's something I didn't get)