Merging and splitting XML files with simpleXML

Here's a way to merge parts of two XML files with PHP's simpleXML. This also preserves the attributes, which was where the information was stored in my case. This script will not work out of the box for you, so edit it. Use var_dump(), print_r() and friends.

<?php
	$file1 = 'file1.xml';
	$file2 = 'file2.xml';
	$fileout = 'fileout.xml';	$xml1 = simplexml_load_file( $file1 );
	$xml2 = simplexml_load_file( $file2 );	// loop through the FOO and add them and their attributes to xml1
	foreach( $xml2->FOO as $foo ) {
		$new = $xml1->addChild( 'FOO' , $foo );
		foreach( $foo->attributes() as $key => $value ) {
			$new->addAttribute( $key, $value );
		}
	}	$fh = fopen( $fileout, 'w') or die ( "can't open file $fileout" );
	fwrite( $fh, $xml1->asXML() );
	fclose( $fh );
?>

And here is a way to split information from one XML file into several:

<?php
	$filein = 'filein.xml';
	$xml = simplexml_load_file( $filein );	foreach( $xml->FOO as $foo ) {
		$foo_id = (string) $foo['Id'];
		$fileout = $foo_id . '.xml';
		$fh = fopen( $fileout, 'w') or die ( "can't open file $fileout" );
		fwrite( $fh, $foo->asXML() );
		fclose( $fh );
	}
?>

Btw, I have noticed a rather odd thing, var_dump()ing a simpleXML object that contains arrays only dumped the array's first element for me, I had to build a foreach() loop to dump the whole array.

3 comments

  1. avatar
    wrote this comment on
    Thanks a lot... saved me a life
  2. avatar
    wrote this comment on
    Hi, I need to merge multiple XML files with the same structure (but with different data) in to one xml file. Basically we have various product feeds and we want to have one master feed. The above post helps but I am getting stuck at the final hurdle. The XML files have the below structure in each XML file: Diesel 500 109.99 new 1234567891234 DW1234 Men's Diesel Watch with Titanium Mechanism Watch 99.99 We would like to merge the products in to one XML file if possible. Thanks in advance.
  3. avatar
    wrote this comment on
    I'm afraid I can't provide free support for such issues, but feel free to contact me if you're interested in hiring me.

Reply

Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.
DjangoPythonBitcoinTuxDebianHTML5 badgeSaltStackUpset confused bugMoneyHackerUpset confused bugX.OrggitFirefoxWindowMakerBashIs it worth the time?i3 window managerWagtailContainerIrssiNginxSilenceUse a maskWorldInternet securityPianoFontGnuPGThunderbirdJenkinshome-assistant-logo