比较和过滤两个xml文件在php


Compare and filter two xml files in php

我想比较PHP中的两个xml文件(实际上是按秒过滤一个),一个xml文件包含例如"interfaces"数据,另一个包含接口(rule.xml),但元素较少,正是我想要的,并希望得到过滤的数据,这是在两个xml。

第一个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>`

第二个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>`

所以我想要的结果是:

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

使用simplexml递归地同步遍历两个xml树。在第一个xml的叶子节点,检查第二个xml中是否出现了相同的节点,并更改值

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