比较并筛选 php 中的两个 xml 文件

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

使用简单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();