How to merge two xml file with PHP

We can merge two xml files which has same xml structure. In our example we will create two xml file and we will merge those with the help of PHP code. So in current folder lets create our sample xml files first. We will keep xml file names as xml_1.xml and xml_2.xml. Both xml files' content mentioned below xml_1.xml will contain below xml


<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
                <item>
                        <name>John</name>
                        <class>XXI</class>
                        <address>USA</address>
                </item>
</rss>
xml_2.xml will contain below xml

<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
                <item>
                        <name>Carloss</name>
                        <class>XX</class>
                        <address>CA</address>
                </item>
                <item>
                        <name>Mark</name>
                        <class>VV</class>
                        <address>UK</address>
                </item>
</rss>
We have below code to merge xml_1.xml and xml_2.xml

<?php
$doc_for_merging = new DOMDocument();
$doc_for_merging->load('xml_2.xml');

$main_doc = new DOMDocument();
$main_doc->formatOutput = true;
$main_doc->load('xml_1.xml');

$items = $doc_for_merging->getElementsByTagName('item');
$counter = 0;
foreach ($items as $item) {
        $newnode = $doc_for_merging->getElementsByTagName('item')->item($counter);
        $newnode = $main_doc->importNode($newnode, true);
        $main_doc->documentElement->appendChild($newnode);
        $counter++;
}

echo $main_doc->saveXML();
//$main_doc->save('updated_file.xml');   // enable it if want to write output in xml file
?>