simpleXML:解析 XML 以仅输出元素属性 [英] simpleXML: parsing XML to output only an elements attributes
问题描述
我正在尝试使用 simpleXML 解析 XML 文件,但我一直遇到问题(请注意,我是 PHP 菜鸟.)
I'm attempting to parse an XML file using simpleXML, but I keep running into issues (mind you I'm a PHP noob.)
这是 XML 文件的结构..(命名约定用于可读性.)
This is the structure of the XML file.. (Naming convention used for readability.)
<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>
所有数据都设置为属性(不是我的决定).我需要能够输出每个属性的名称属性,以及指示状态的第二个属性.大陆"将是唯一的,但每个大陆"可以有多个国家"和城市".
All of the data is set as attributes (not my decision.) I need to be able to output the name attribute of each of these, as well as a second attribute that tells the status. The "Continents" will be unique, but each "Continent" is allowed to have multiple "Countries" and "Cities."
这是我目前拥有的 PHP...
This is the PHP that I currently have...
<?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,但我很难开始.另外,我如何确保所有城市都出现,而不仅仅是第一个?
How can I avoid having to repeat myself and going level by level using ->? I thought I could use xpath, but I had a tough time getting started. Also, how can I make sure all of the cities show up and not just the first one?
推荐答案
您可能没有循环"这些国家和城市:
You were probably not "cycling" the countries and cities:
<?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
}
?>
这篇关于simpleXML:解析 XML 以仅输出元素属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!