Compare and filter two xml files in php

I want to compare two xml files in PHP (actually filter one to a second), one XML file contains for example "interface" data, the other contains interfaces (rule.xml) but with fewer elements that I definitely want and want get the filtered data that is in both xmls.

First xml:

`<?xml version="1.0" encoding="UTF-8"?>
<data>
  <interfaces>
    <interface>
        <name><!-- type: string --></name>
        <type><!-- type: string --></type>
        <mtu><!-- type: int32 --></mtu>
    <interface>
</interfaces>
</data>`

      

Second xml:

`<?xml version="1.0" encoding="UTF-8"?>
<data>
  <interfaces>
    <interface>
      <name>interfacename</name>
      <type>gigaeth</type>
      <mtu>1500</mtu>
      <counters>
        <inBytes>17800</inBytes>
        <inPackets>156000</inPackets>
        <inErrors>850</inErrors>
      </counters>
    </interface>
  </interfaces>
</data>`

      

Thus, I want:

`<?xml version="1.0" encoding="UTF-8"?>
<data>
  <interfaces>
    <interface>
      <name>interfacename</name>
      <type>gigaeth</type>
      <mtu>1500</mtu>
   </interface>
  </interfaces>
</data>`

      

+3


source to share


1 answer


Using simplexml to recursively traverse both xml trees synchronously. On the sheet node of the first xml check that the same node is present in the second and change the value



$xml1 = new SimpleXMLElement($str1);
$xml2 = new SimpleXMLElement($str2);

function set(&$xml, $xml2) {
    foreach($xml as $key => $xmlpos) {
        if (isset($xml2->$key))
          if($xmlpos->count()) set($xmlpos, $xml2->$key);
          else  $xml->$key =  $xml2->$key;
    }
}

set($xml1, $xml2);
echo $xml1->saveXML(); 

      

+2


source







All Articles