【问题标题】:simpleXML: parsing XML to output only an elements attributessimpleXML:解析 XML 以仅输出元素属性
【发布时间】:2013-02-04 22:05:26
【问题描述】:

我正在尝试使用 simpleXML 解析 XML 文件,但我一直遇到问题(请注意,我是 PHP 菜鸟。)

这是 XML 文件的结构。(用于提高可读性的命名约定。)

<World>
  <Continent Name="North America" Status="" >
   <Country Name="United States of America" Status="">
     <City Name="New York" Status="" />
     <City Name="Chicago" Status="" />
   </Country>
  </Continent>
</World>

所有数据都设置为属性(不是我的决定。)我需要能够输出每个属性的名称,以及告诉状态的第二个属性。 “大陆”将是唯一的,但每个“大陆”可以有多个“国家”和“城市”。

这是我目前拥有的 PHP...

<?php
        $xml_file = '/path';
        $xml = simplexml_load_file($xml_file);

        foreach($xml->Continent as $continent) {
            echo "<div class='continent'>".$continent['Name']."<span class='status'>".$continent['Status']."</span></div>";
            echo "<div class='country'>".$continent->Country['Name']."<span class='status'>".$continent->Country['Status']."</span></div>";
            echo "<div class='city'>".$continent->Country->City['Name']."<span class='status'>".$continent->Country->City['Status']."</span></div>";
         }

?>

如何避免重复自己并逐级使用 ->?我以为我可以使用 xpath,但我很难开始。另外,我怎样才能确保所有城市都出现,而不仅仅是第一个?

【问题讨论】:

  • 您需要三个嵌套的foreach:(1)foreach Continent,(2)foreach Country,和(3)foreach City。这样你就可以覆盖 xml 文档中的其他内容
  • 我想过这个问题,也许我完全搞砸了,但是当我嵌套 foreach 时,它会返回所有正确的大陆名称,但随后每个大陆都会返回第一个大陆的国家。 (即北美:美国、加拿大 | 南美:美国、加拿大 | 非洲:美国、加拿大)等等。

标签: php xml xpath simplexml


【解决方案1】:

您可能没有“骑自行车”国家和城市:

<?php
    $xml_file = '/path';
    $xml = simplexml_load_file($xml_file);

    foreach($xml->Continent as $continent) {
        echo "<div class='continent'>".$continent['Name']."<span class='status'>".$continent['Status']."</span>";
        foreach($continent->Country as $country) {
            echo "<div class='country'>".$country['Name']."<span class='status'>".$country['Status']."</span>";
            foreach($country->City as $city) {
                echo "<div class='city'>".$city['Name']."<span class='status'>".$city['Status']."</span></div>";
            }
            echo "</div>"; // close Country div
        }
        echo "</div>"; // close Continent div
    }
?>

【讨论】:

  • 你也打败了我,我打算用不同的方式打出来,可能会错而且更冗长,我是从 xPath 的角度思考,而不是从 PHP 角度思考观点。 PHP 不是我的母语..lol
  • 刚刚看到循环逻辑中的一个小缺陷 :)
  • 爱上 PHP 的“冗长”... B)
  • 太棒了,谢谢!我知道这一定是我忽略的一些简单的事情。
  • 一看到你写的就点击了!
猜你喜欢
  • 2015-12-23
  • 1970-01-01
  • 1970-01-01
  • 2013-08-14
  • 2015-02-06
  • 2012-04-13
  • 2010-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多