简体   繁体   中英

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>`

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM