【发布时间】: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 时,它会返回所有正确的大陆名称,但随后每个大陆都会返回第一个大陆的国家。 (即北美:美国、加拿大 | 南美:美国、加拿大 | 非洲:美国、加拿大)等等。