如何遍历两个 XML 文件并打印结果

How to loop through two XML files and print result

我一直在尝试使用 PHP 循环两个 XML 文件并将结果打印到屏幕上,但没有成功。目的是获取一个国家的名称并根据情况输出其regions/states/provinces。

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

国家文件的格式为:

<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>";
    }
   }
}

我哪里做错了? 谢谢。

我怀疑您的问题是在进行比较之前没有将名称转换为字符串。但是为什么在检查是否需要之前开始第二个循环?您正在不必要地遍历 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/>";
        }
    }
}

此外,请注意,以描述性方式命名变量可以更轻松地弄清楚代码的运行情况。


您可以使用对 match the sibling value 的 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/>";
}