0

我正在尝试从 XML 文件中输出数据。

以下是 XML 文件的摘录:

<TAF>
<raw_text>
TAF AMD EGBB 242124Z 2421/2518 11006KT 6000 BKN020 TEMPO 2421/2424 4000 +SHRA TSRA BECMG 2421/2424 BKN009 PROB30 2500/2506 4000 BR BKN004 BECMG 2506/2508 9999 SCT020 TEMPO 2508/2518 7000 SHRA PROB30 TEMPO 2508/2518 33015G25KT 4000 +TSRA BECMG 2515/2518 35010KT
</raw_text>
<station_id>EGBB</station_id>
<issue_time>2012-08-24T21:24:00Z</issue_time>
<valid_time_from>2012-08-24T21:00:00Z</valid_time_from>
<valid_time_to>2012-08-25T18:00:00Z</valid_time_to>

<forecast>
    <fcst_time_from>2012-08-24T21:00:00Z</fcst_time_from>
    <fcst_time_to>2012-08-25T18:00:00Z</fcst_time_to>
    <wind_dir_degrees>110</wind_dir_degrees>
    <wind_speed_kt>6</wind_speed_kt>
    <visibility_statute_mi>3.73</visibility_statute_mi>
    <sky_condition sky_cover="BKN" cloud_base_ft_agl="2000"/>
</forecast>
<forecast>
    <fcst_time_from>2012-08-24T21:00:00Z</fcst_time_from>
    <fcst_time_to>2012-08-25T00:00:00Z</fcst_time_to>
    <change_indicator>TEMPO</change_indicator>
    <visibility_statute_mi>2.49</visibility_statute_mi>
    <wx_string>+SHRA TSRA</wx_string>
</forecast>
</TAF>

也许还有几个<forecast>。我的问题是如何将它们填充到 foreach 循环中以输出<forecast>下每个元素的数据<TAF>

我目前正在使用:

$xml_taf->data->TAF[0]->forecast

使用 SimpleXML 访问 XML 中的数据。

4

1 回答 1

1

我不确定你在做什么,但这有效

$xml = '<TAF>
<raw_text>
TAF AMD EGBB 242124Z 2421/2518 11006KT 6000 BKN020 TEMPO 2421/2424 4000 +SHRA TSRA BECMG 2421/2424 BKN009 PROB30 2500/2506 4000 BR BKN004 BECMG 2506/2508 9999 SCT020 TEMPO 2508/2518 7000 SHRA PROB30 TEMPO 2508/2518 33015G25KT 4000 +TSRA BECMG 2515/2518 35010KT
</raw_text>
<station_id>EGBB</station_id>
<issue_time>2012-08-24T21:24:00Z</issue_time>
<valid_time_from>2012-08-24T21:00:00Z</valid_time_from>
<valid_time_to>2012-08-25T18:00:00Z</valid_time_to>

<forecast>
    <fcst_time_from>2012-08-24T21:00:00Z</fcst_time_from>
    <fcst_time_to>2012-08-25T18:00:00Z</fcst_time_to>
    <wind_dir_degrees>110</wind_dir_degrees>
    <wind_speed_kt>6</wind_speed_kt>
    <visibility_statute_mi>3.73</visibility_statute_mi>
    <sky_condition sky_cover="BKN" cloud_base_ft_agl="2000"/>
</forecast>
<forecast>
    <fcst_time_from>2012-08-24T21:00:00Z</fcst_time_from>
    <fcst_time_to>2012-08-25T00:00:00Z</fcst_time_to>
    <change_indicator>TEMPO</change_indicator>
    <visibility_statute_mi>2.49</visibility_statute_mi>
    <wx_string>+SHRA TSRA</wx_string>
</forecast>
</TAF>';

echo "<pre>";
$xml = new SimpleXMLElement($xml);
foreach ( $xml->forecast as $forecast ) {
    print( $forecast->fcst_time_from . ","  . $forecast->fcst_time_to . "," . $forecast->visibility_statute_mi . PHP_EOL);
}

输出

2012-08-24T21:00:00Z,2012-08-25T18:00:00Z,3.73
2012-08-24T21:00:00Z,2012-08-25T00:00:00Z,2.49

观看现场演示

于 2012-10-10T09:00:55.007 回答