简体   繁体   中英

Getting attributes from XML in PHP

I'm trying to get attributes from an XML file using this code:

$xmlFile = "http://weather.aero/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&stationString=".$_GET['station']."&hoursBeforeNow=1";

$xml = simplexml_load_file($xmlFile);

This is the XML file:

<response xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XML-Schema-instance" version="1.2" xsi:noNamespaceSchemaLocation="http://weather.aero/schema/metar1_2.xsd">
<request_index>29916745</request_index>
<data_source name="metars"/>
<request type="retrieve"/>
<errors/>
<warnings/>
<time_taken_ms>2</time_taken_ms>
<data num_results="1">
<METAR>
<raw_text>EGHH 241850Z 17014KT 9999 BKN006 17/16 Q1000</raw_text>
<station_id>EGHH</station_id>
<observation_time>2012-08-24T18:50:00Z</observation_time>
<latitude>50.78</latitude>
<longitude>-1.83</longitude>
<temp_c>17.0</temp_c>
<dewpoint_c>16.0</dewpoint_c>
<wind_dir_degrees>170</wind_dir_degrees>
<wind_speed_kt>14</wind_speed_kt>
<visibility_statute_mi>6.21</visibility_statute_mi>
<altim_in_hg>29.52756</altim_in_hg>
<sky_condition sky_cover="BKN" cloud_base_ft_agl="600"/>
<flight_category>IFR</flight_category>
<metar_type>METAR</metar_type>
<elevation_m>11.0</elevation_m>
</METAR>
</data>
</response>

Now, I'm able to extract other information, but to get the attributes for , I'm using this:

<?php foreach ($xml->data->METAR[0]->sky_conditions->attributes() as $sky_cover => $cloud_base_ft_agl){

            echo"<tr>";
            echo"<td><strong>";
            if ($sky_cover == "CAVOK") {echo "Ceiling and Visibility OK";} else {echo $val['sky_cover'];}
            echo"</strong></td>";
            echo"<td><strong>";
            if (isset($cloud_base_ft_agl)){echo $cloud_base_ft_agl; }
            echo"</strong></td>";
            echo"</tr>";
        }?>

However, I'm getting the error: Warning: main() [function.main]: Node no longer exists in

Any ideas on how I can fix this?

sky_conditions does not exit Which does not exist .. please note that sky_condition not in $xml->data->METAR[0]->sky_conditions->attributes()

This would fix the issue

$td = "<tr><td><strong>%s</strong></td><td><strong>%s</strong></td></tr>";
echo '<table>';
foreach ( $xml->data->METAR[0]->sky_condition as $value ) {
    $attribute = $value->attributes();
    printf($td, $attribute['sky_cover'], $attribute['cloud_base_ft_agl']);
}
echo '</table>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM