2012-11-12 39 views
0

可能重複:
php simplexml issue in reading an attribute that has a ‘column - : ’ in its name使用SimpleXML來抓住嵌套代碼

我在學習PHP的過程,所以我在做一個天氣應用程序顯示基於圖像關於天氣。我正在使用Yahoo Weather API。

我的問題是,我正在尋找一種方式來攫取the code of the weather, located next to yweather:condition。我發現simpleXML但無法弄清楚如何抓住東西是位於像雅虎確實它的XML在

<yweather:condition text="Fair" code="34" temp="37" 

形式的方式所以我的問題是我怎麼能搶碼=「34」雅虎天氣的一部分,並顯示它像一個變量,如$weathercode = 34;

感謝任何及所有的幫助,我在這裏,如果你需要他們提供更多的細節!

此外,我不知道這文章的標題是正確的,很抱歉,如果它不是!

+0

尋找http://stackoverflow.com/search?q=yweather+simplexml產生大量的成果。詢問前請使用搜索。謝謝。 – Gordon

回答

1

可以使用的SimpleXMLElement ::類似的方式屬性調用下面。

$string = {Yahoo Weather Feed} 

$xml = simplexml_load_string($string); 

$weathercode = $xml->channel->item->children('yweather', true)->condition[0]->attributes()->code; 

您可能需要修補以確保正確,但這只是一個指導。

參考:http://php.net/manual/en/simplexmlelement.attributes.php

+0

感謝您的答覆。這隻會得到'code =「34」'一次嗎?因爲'code =「34」'隨着天氣的變化而變化,所以有時候可能是'code =「50」'或'code =「30」' – Muhambi

+0

我用一些實際上有用的東西更新了我的答案。 –

+0

你是一個很棒的StackOverflow-er謝謝你 – Muhambi

0

你可以嘗試以下方法:

$xml = simplexml_load_file('http://weather.yahooapis.com/forecastrss?w=12793465&u=f'); 
var_dump($xml); 

這將加載URL和轉儲SimpleXML的對象。

More on simplexml_load_file here

+0

請不要在SimpleXML中使用'var_dump()';它會導致你誤入歧途。嘗試其中之一,而不是:https://github.com/imsop/simplexml_debug – IMSoP