0

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>

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.