2017-06-27 115 views
0

我試圖解析使用PHP SimpleXML擴展以下XML天氣預報數據解析XML的天氣預報數據:使用PHP和SimpleXML

http://www.pakenhamweather.info/test/IDV10753.xml

我已經嘗試了很多次來解析這個XML但徒勞無功。下面是一個例子:

$product = simplexml_load_file("http://www.pakenhamweather.info/test/IDV10753.xml"); 

foreach ($product->forecast->area[2]->forecast-period[0] as $blah) { 
    printf(
    "<p>Forecast Icon: $s</p><p>Precipitation Range: $s</p>" 
    $blah->element["forecast_icon_code"] 
    $blah->element["precipitation_range"] 
    ); 
} 

對於此示例的目的,我已經通過選擇簡化了例如「區域[2]」和「預測週期[0]」,但理想的是,我想根據'index'屬性,通過'description'屬性和'forecast-period'指定'area'。

任何幫助將不勝感激。先謝謝你。

+0

_「但最好的屬性值,我想通過‘描述’屬性和‘預測期’基於指定‘區域’的'索引'屬性「_ - 那麼你應該去查看XPath。 – CBroe

回答

0

您可以嘗試使用以下代碼獲取按屬性和按屬性預測的區域。

$product = simplexml_load_file("http://www.pakenhamweather.info/test/IDV10753.xml"); 
$forecasts = $product->forecast->xpath("//area[@description='Mildura']/forecast-period[@index='1']"); 
foreach ($forecasts as $forecast) { 
    $forecast_icon_code = $forecast->xpath("element[@type='forecast_icon_code']")[0]; 
    $precipitation_range = $forecast->xpath("element[@type='precipitation_range']")[0]; 
    echo $forecast_icon_code . "===" . $precipitation_range; 
} 

只需更換要挑

+0

這正是我所需要的!非常感謝dileep-kumar幫助我。儘管閱讀了他們兩個,但我從來沒有在simplexml和xpath之間建立聯繫。 – theloneisobar