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
Reply