我是这个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://aviationweather.gov/adds/schema/metar1_2.xsd">
<request_index>471527627</request_index>
<data_source name="metars"/>
<request type="retrieve"/>
<errors/>
<warnings/>
<time_taken_ms>20</time_taken_ms>
<data num_results="1">
<METAR>
<raw_text>
EDDF 121020Z 20011KT 9999 FEW032 BKN130 05/01 Q1013 R88/CLRD// NOSIG
</raw_text>
<station_id>EDDF</station_id>
<observation_time>2017-01-12T10:20:00Z</observation_time>
<latitude>50.05</latitude>
<longitude>8.6</longitude>
<temp_c>5.0</temp_c>
<dewpoint_c>1.0</dewpoint_c>
<wind_dir_degrees>200</wind_dir_degrees>
<wind_speed_kt>11</wind_speed_kt>
<visibility_statute_mi>6.21</visibility_statute_mi>
<altim_in_hg>29.911417</altim_in_hg>
<quality_control_flags>
<no_signal>TRUE</no_signal>
</quality_control_flags>
<sky_condition sky_cover="FEW" cloud_base_ft_agl="3200"/>
<sky_condition sky_cover="BKN" cloud_base_ft_agl="13000"/>
<flight_category>VFR</flight_category>
<metar_type>SPECI</metar_type>
<elevation_m>113.0</elevation_m>
</METAR>
</data>
</response>
在底部有两行具有相同名称:
<sky_condition sky_cover="FEW" cloud_base_ft_agl="3200"/>
<sky_condition sky_cover="BKN" cloud_base_ft_agl="13000"/>
如何使用PHP获取这两个名称的属性? 我会有这样的输出:
FEW 3200
BKN 13000
非常感谢!!此致,Philipp
答案 0 :(得分:1)
尝试这样:
$xml_obj = simplexml_load_string($xml);
$sk_cond = $xml_obj->data->METAR->sky_condition;
foreach ($sk_cond as $cond) {
echo $cond->attributes()->{'sky_cover'} . ' ' . $cond->attributes()->{'cloud_base_ft_agl'} . PHP_EOL;
}
答案 1 :(得分:0)
我认为您可以使用DomDocument来实现它。这是处理XML的一种冗长的方式,但很好理解你在做什么。
$doc = new DOMDocument();
$doc->loadXML($xml);
$skyConds = $doc->getElementsByTagName('sky_condition');
foreach ($skyConds as $sk) {
$skyCover = $sk->getAttribute('sky_cover');
$cbfa = $sk->getAttribute('cloud_base_ft_agl');
print_r ("FEW $skyCover $cbfa" . "\n");
}