How do I merge xml files into one using PHP?

Josh Gomez Source

So Im having a bit of trouble understanding how to merge three xml files into one xml file using PHP.

Ive made a start but Im having difficulty, first off here is my xsl which separates a xml into 3 groups by country with the file names as "CD1_USA.xml", CD2_UK UK UK.xml" and "CD2_AU AU.xml":


<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="">
<xsl:output method="xml" indent="yes" name="cd-format"/>
<xsl:template match="/">
<xsl:for-each-group select="/CATALOG//CD" group-by="COUNTRY">
    <xsl:result-document href="CD{position()}_{current-group()/COUNTRY}.xml" format="cd-format">

    <CD_LIST country="{current-group()/COUNTRY}">
        <xsl:copy-of select="current-group()"/>


Now using PHP I need to merge these 3 xml into one file named "mergeFile.xml"

So Ive started to make an attempt but Im a bit lost from here because the mergeFile must have the prolog

<?xml version="1.0" encoding="UTF-8"?>    

Some guidance is appreciated from this point


// Read file 1
$xmlfilecontent = file_get_contents('CD1_USA.xml');

// Concat file 2
$xmlfilecontent .= file_get_contents('CD2_UK UK UK.xml');

//Concat file 3
$xmlfilecontent .= file_get_contents('CD2_AU AU.xml');


answered 6 months ago Harsh Barach #1

You should store data into Array.

    $xmlfilecontent = array();

    // Read and Insert file 1 into array
    $xmlfilecontent[] = file_get_contents('CD1_USA.xml');

    // Read and Insert file 2 into array
    $xmlfilecontent[] = file_get_contents('CD2_UK UK UK.xml');

    // Read and Insert file 3 into array
    $xmlfilecontent[] = file_get_contents('CD2_AU AU.xml');


comments powered by Disqus