Best method for combining 2 XML files?

I have two xml files; source.xml and archive.xml. They are the same structure;

<food>
	<name>Bagels, New York Style </name>
	<id>1</id>
	<link>www.link.com</link>
</food>

What would be the best method of making one .xml from both? Ideally writing source.xml to the end of archive.xml

Someone has helped me with a function that converts each file to an array but as they are the same structure one is over written when I try to merge them.

<?php
function xml2array($fname){
  $sxi = new SimpleXmlIterator($fname, null, true);
  return sxiToArray($sxi);
}

function sxiToArray($sxi){
  $a = array();
  for( $sxi->rewind(); $sxi->valid(); $sxi->next() ) {
    if(!array_key_exists($sxi->key(), $a)){
      $a[$sxi->key()] = array();
    }
    if($sxi->hasChildren()){
      $a[$sxi->key()][] = sxiToArray($sxi->current());
    }
    else{
      $a[$sxi->key()][] = strval($sxi->current());
    }
  }
  return $a;
}

// Read source.xml and convert to array:
$sourceArray = xml2array('source.xml');

/// merge 2 arrays
$array1 = $archiveArray;
$array2 = $sourceArray;
$result = array_merge($array1, $array2);
print_r($result);////print 'merged' result

Am I approaching this the wrong way?

Maybe I am being simplistic, but cant you just chop the first 2 lines (say) off the start your new file - and 2 lines off the end of your old file and just append the contents of the new file to the old one?

I say 2 lines, but it might be more or less depending on the structure of the file.

Do you actually want to merge the two files, to create one file? Or maybe just be able to use both files in a script?

Me? Overcomplicating things? Never! :slight_smile:

I did actually think about this approach to start with but thought as I’m using XML I should be using the XML classes.

I woulldnt even need to chop anything as I want to keep the <food> node anyway.

I think i know how to open and write to a file but How do I do detect the end of a line?

I want to end up with Archive.XML being a file that source.XML is written to every so often. Archive will then be used for other things.