Junior12
Junior12

Reputation: 29

Compare and filter two xml files in php

I want to compare two xml files in PHP (actually filter one by the second), one xml file contains for example "interfaces" data another contains interfaces(rule.xml) but with less elements just what i want exactly, and want to get filtered data which is in both of 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>`

So the result that i want is :

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

Upvotes: 3

Views: 956

Answers (1)

splash58
splash58

Reputation: 26153

Using simplexml to recursively walk both xml trees synchronously. At leaf node of the first xml check that the same node presents in the second one 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(); 

Upvotes: 2

Related Questions