【问题标题】:How to compare Two XML files for same atribute names by php如何通过php比较两个具有相同属性名称的XML文件
【发布时间】:2017-03-27 19:14:12
【问题描述】:

我有两个 XML 文件 string1.xmlstring2.xml 每个文件都包含更多的行代码。我想根据相同的 attr 名称比较两个 XML 文件

我想像下面这个表达式一样对所有行进行迭代循环

if (attribute name cancel in string1.xml also found in string2.xml) {
    echo '<string name="attrName from string1.xml">Atribute Value from string2.xml</string>'
} else {
    echo '<string name="attrName from string1.xml">Atribute Value from string1.xml</string>'
}

string1.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="cancel">Cancel</string>
    <string name="copy">Copy</string>
    <string name="copyUrl">Copy URL</string>
</resources>

string2.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="cancel">US</string>
    <string name="paste">Italy</string>
    <string name="copyUrl">Germany</string>
</resources>

【问题讨论】:

  • 键总是匹配的吗?您是否尝试过使用SimpleXML?结构是单层还是多层?
  • 这里看看如何检查一个属性是否可用stackoverflow.com/questions/10909372/…
  • @mkaatman 是的结构始终是单层我尝试了单个 XML 文件的 SimpleXML,但我尝试与失败的文件进行比较我无法创建正确的 foreach 循环以遍历两个文件中的所有行跨度>
  • @mkaatman 两个文件的属性名略有不同,但属性值完全不同

标签: php xml


【解决方案1】:

你可以这样做:

<?php

$resource1 = new SimpleXMLElement($xml);
$resource2 = new SimpleXMLElement($xml);

$array1 = $resource1->string;
$array2 = $resource2->string;

$differences = array_diff($array1, $array2);

或者,也许您可​​以遍历第一个以查找第二个中的项目。

foreach($array1 as $key => $value) { if(array_key_exists($key, $array2) && $array1[$key] === $array2[$key] ) { echo "$key is the same."; } }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    • 2021-12-18
    • 2018-01-01
    • 2010-12-16
    相关资源
    最近更新 更多