I am new to PHP programming and would appreciate whatever help i can get. I have an Xml file that looks like below..
<?xml version="1.0" encoding="UTF-8"?> <results> <test external_id="123"> <result>p</result> </test> <test external_id="1237"> <result>p</result> </test> <test external_id="234"> <result>p</result> </test> <test external_id="678"> <result>p</result> </test> </results> The XML file is generated from a testrun. Now sometimes the test could break and would restart generating another xml file which might contain similar values as generated in the first xml file. For example, Xml file 2 might contain the following values
<?xml version="1.0" encoding="UTF-8"?> <results> <test external_id="412"> <result>p</result> </test> <test external_id="234"> <result>p</result> </test> <test external_id="123"> <result>p</result> </test> <test external_id="745"> <result>p</result> </test> </results> I need to write a PHP script to merge the different XML files generated into a single XML file without duplicates. Only one occurrence of (test external_id = "XXX")should be in the final xml file. There could be more than 2 XML files generated during the test run. I have searched through the various solutions given on stackoverflow but can't get it. I have been able to merge the files but the duplicates are still there.What I have written so far. Thanks for your anticipated help.
<?php $doc1 = new DOMDocument(); $doc1->load('11.xml'); $doc2 = new DOMDocument(); $doc2->load('12.xml'); // get 'results' element of document 1 $res1 = $doc1->getElementsByTagName('results')->item(0); // iterate over 'testcase' elements of document 2 $items2 = $doc2->getElementsByTagName('test'); 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'); //saving into xml file $seen=array(); $doc3 = new DOMDocument(); $doc3->load('merged.xml'); $results = $doc3->getElementsByTagName('test'); foreach($results as $test){ //$key=$doc3->$test; if (isset($seen[$test])) { unset($doc3->$test); }else{ $seen[$test]=1; } } echo $doc3->asXML(); ?>
$seen=array(); $doc3 = new DOMDocument(); $doc3->load('merged.xml'); $results = $doc3->getElementsByTagName('test'); foreach($results as $test){ //$key=$doc3->$test; if (isset($seen[$test])) { unset($doc3->$test); }else{ $seen[$test]=1; } } echo $doc3->asXML();