php – Insert an xml element from an xml doc to an other xml document – Education Career Blog

Let’s say I have to xml documents:

<first_root>
  <element1/>
  <element2>
    <embedded_element/>
  </element2>
</first_root>

and

<foo>
  <bar/>
</foo>

How can I put this second xml doc into the first one, using php and DomDocument or SimpleXML?

I want it to look like something like this:

<first_root>
  <element1/>
  <element2>
    <foo>
      <bar/>
    </foo>
    <embedded_element/>
  </element2>
</first_root>

,

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 DOMDocuments, 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)

Leave a Comment