首页 > 解决方案 > 如何遍历两个 XML 文件并打印结果

问题描述

我一直在尝试使用 PHP 循环遍历两个 XML 文件并将结果打印到屏幕上,但没有成功。目的是取一个国家的名字,并视情况输出其地区/州/省。

第一个代码块成功地打印了所有国家,但是通过两个文件的循环给了我一个空白屏幕。

国家文件格式为:

<row>
    <id>6</id>
    <name>Andorra</name>
    <iso2>AD</iso2>
    <phone_code>376</phone_code>
  </row> 

和 states.xml:

<row>
    <id>488</id>
    <name>Andorra la Vella</name>
    <country_id>6</country_id>
    <country_code>AD</country_code>
    <state_code>07</state_code>
  </row>

所以 country_id = id。

这给出了一个完美的国家列表:

$xml = simplexml_load_file("countries.xml");
$xml1 = simplexml_load_file("states.xml");

foreach($xml->children() as $key => $children) {
  print((string)$children->name); echo "<br>";
}

除了页面上的 HTML 内容外,这给了我一个空白屏幕:

$xml = simplexml_load_file("countries.xml");
$xml1 = simplexml_load_file("states.xml");
$s = "Jamaica";
foreach($xml->children() as $child) {
  foreach($xml1->children() as $child2){ 
    if ($child->id == $child2->country_id && $child->name == $s) {
        print((string)$child2->name);
        echo "<br>";
    }
   }
}

我哪里出错了?谢谢。

标签: phpxmlsimplexml

解决方案


我怀疑您的问题是在进行比较之前没有将名称转换为字符串。但是为什么在检查是否需要之前开始第二个循环呢?states.xml您正在不必要地循环遍历每个项目。

$countries = simplexml_load_file("countries.xml");
$states = simplexml_load_file("states.xml");
$search = "Jamaica";

foreach($countries->children() as $country) {
    if ((string)$country->name !== $search) {
        continue;
    }
    foreach($states->children() as $state) { 
        if ((string)$country->id === (string)$state->country_id) {
            echo (string)$state->name . "<br/>";
        }
    }
}

另外,请注意,以描述性方式命名变量可以更容易地弄清楚代码发生了什么。


您可以完全摆脱循环,使用 XPath 查询来匹配兄弟值。我不使用 SimpleXML,但这是使用 DomDocument 的样子:

$search = "Jamaica";

$countries = new DomDocument();
$countries->load("countries.xml");
$xpath = new DomXPath($countries);
$country = $xpath->query("//row[name/text() = '$search']/id/text()");
$country_id = $country[0]->nodeValue;

$states = new DomDocument();
$states->load("states.xml");
$xpath = new DomXPath($states);
$states = $xpath->query("//row[country_id/text() = '$country_id']/name/text()");
foreach ($states as $state) {
    echo $state->nodeValue . "<br/>";
}

推荐阅读