在PHP中从XML获取属性


Getting attributes from XML in PHP

我正试图使用以下代码从XML文件中获取属性:

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

这是XML文件:

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

现在,我可以提取其他信息,但为了获得的属性,我使用的是:

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

然而,我得到了一个错误:警告:main()[function.main]:中不再存在节点

关于我该怎么解决这个问题,有什么想法吗?

sky_conditions不退出,不存在。。请注意,sky_condition不在$xml->data->METAR[0]->sky_conditions->attributes()

这将解决问题

$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>';