在 PHP 中从 XML 获取属性 [英] Getting attributes from XML in PHP

查看:31
本文介绍了在 PHP 中从 XML 获取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

现在,我可以提取其他信息,但要获取 的属性,我正在使用:

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

但是,我收到错误消息:警告:main() [function.main]:节点不再存在于

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 .. 请注意 sky_conditions 不在 中$xml->data->METAR[0]->sky_conditions->attributes()

sky_conditions does not exit Which does not exist .. please note that sky_condition not in $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>';

这篇关于在 PHP 中从 XML 获取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆