2017-01-12 177 views
1

attribut我有這個XML獲取XML數據與PHP

<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

非常感謝您!此致,菲利普

回答

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; 
} 
+0

非常感謝! – Philipp

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