simpleXML: parsing XML to output only an elements attributes

烂漫一生 提交于 2019-12-11 02:15:41

问题


I'm attempting to parse an XML file using simpleXML, but I keep running into issues (mind you I'm a PHP noob.)

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."

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

?>

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?


回答1:


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
    }
?>


来源:https://stackoverflow.com/questions/14696533/simplexml-parsing-xml-to-output-only-an-elements-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!