dimanche 28 juin 2015

How to change a php code to merge any number of XML files

Here the working code (i took here) to merge two XML files into one. It is working properly, but only with 2 parts of xml.

<?php
$numparts=2;
$filename1='TEST_1.xml';
$filename2='TEST_2.xml';
$doc1 = new DOMDocument();
$doc1->load($filename1);

$doc2 = new DOMDocument();
$doc2->load($filename2);

// get 'res' element of document 1
$res1 = $doc1->getElementsByTagName('items')->item(0); //edited res - items

// iterate over 'item' elements of document 2
$items2 = $doc2->getElementsByTagName('item');

for ($i = 0; $i < $items2->length; $i ++) {
$item2 = $items2->item($i);

// import/copy item from document 2 to document 1
$item1 = $doc1->importNode($item2, true);

// append imported item to document 1 'res' element
$res1->appendChild($item1);
}
$doc1->save('merged.xml'); //edited -added saving into xml file
?>

Please help to change the code to work with any number of pieces (stored in the variable $numparts).

Aucun commentaire:

Enregistrer un commentaire