jamo54
jamo54

Reputation: 3

Combining XML files in php

I am getting external xml files (through file exchange) and I am able to read and store in the database (php/mysql). The xml files come zipped under different names and sometimes several files come together zipped in a folder

When the folder has only 1 xml file,I am able to successfully unzip and read the content using

 $path = '/xmlFile'; 
   //the xmlFile names are in this format : xmFile-00001235.xml, 
   //xmlFile-000012390.xml, etc.   only first portions are consistent

   foreach (glob($path.'/xmlFile-*.xml') as $filename) 

  {
  $xml=file_get_contents($filename);    

   }
   //store in database and unlink the xml file

This only works if the folder has one xml file, because I am un-linking the xml file after storage, it un-links all the files but only stores one

What would be the best approach; I am thinking of checking if the folder has more than 1 xml and combine the xml files? maybe a sample solution will really help,

The sample xml is as follows

xml1.xml

<sales>
    <row id="000001" saleid="267158" amountSold="2000"  />
    <row id="000001" saleid="267159" amountSold="80.000" />
 </sales>

xml2.xml

  <sales>
    <row id="000001" saleid="267160" amountSold="4000"  />
    <row id="000001" saleid="267161" amountSold="580" />
   </sales>

Upvotes: 0

Views: 2349

Answers (2)

Azrideus
Azrideus

Reputation: 85

Based on the answer in: Merge XML files in PHP

$doc1 = new DOMDocument();
$doc1->load('1.xml');

$doc2 = new DOMDocument();
$doc2->load('2.xml');

// 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);

}

Upvotes: 1

Nigel Ren
Nigel Ren

Reputation: 57141

Merging several files can be done something like...

function mergeFile ( DOMDocument $target, $fileName )    {
    $source = new DOMDocument();
    $source->load($fileName);

    foreach ( $source->getElementsByTagName("row") as $row )   {
        $import = $target->importNode($row, true);
        $target->documentElement->appendChild($import);
    }
}

$target = new DOMDocument();
$target->loadXML('<?xml version="1.0" encoding="utf-8"?><sales></sales>');
mergeFile($target, "NewFile.xml");
mergeFile($target, "NewFile1.xml");
mergeFile($target, "NewFile2.xml");

$target->save("out2.xml");

This allows you to keep on adding all of the files together and then saving them at the end.

Upvotes: 1

Related Questions