simpleXML: parsing XML to output only an elements

2019-07-20 08:08发布

问题:

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