2011-06-02 174 views
1

我正在嘗試從雅虎閱讀我的網站的天氣信息。 使用下面的代碼我能夠打印XML。 我真正想要的,現在實現的是把溫度和圖像在兩個不同的變量如何用php解析XML

$zipCode = "44418"; 
$url = "http://weather.yahooapis.com/forecastrss"; 
$zip = "?w=$zipCode"; 
$fullUrl = $url . $zip.'&u=c'; 
$curlObject = curl_init(); 
curl_setopt($curlObject,CURLOPT_URL,$fullUrl); 
curl_setopt($curlObject,CURLOPT_HEADER,false); 
curl_setopt($curlObject,CURLOPT_RETURNTRANSFER,true); 
$returnYahooWeather = curl_exec($curlObject); 
curl_close($curlObject); 
print "yahooWeather". $returnYahooWeather; 

//$temperature 
//$image 
+0

所以你折現的最佳解決方案(一[DOM文檔(http://php.net/manual/en/class.domdocument.php))馬上?聽起來很有希望。 – 2011-06-02 14:31:00

+0

我同意下面的答案,使用simplexml或DOM應該這樣做。但是你也不應該從預處理函數裏面打印/回顯。相反,創建一個可以在模板中使用的變量。例如'$ variables ['temperature'] = TEMP CODE HERE;'然後在模板中你只需要做'<?php print $ temperature; ?>' – Laxman13 2011-06-02 14:55:53

+0

@ Laxman13,我意識到這一點,謝謝。只需要看看前往tpl.php文件之前發生了什麼:) – seun 2011-06-02 15:03:19

回答

3

您應該繼續使用simplexmlDOM解析XML,然後您可以遍歷結果。用SimpleXML這看起來是這樣的:

$zipCode = "44418"; 
$url = "http://weather.yahooapis.com/forecastrss"; 
$zip = "?w=$zipCode"; 
$fullUrl = $url . $zip.'&u=c'; 
$curlObject = curl_init(); 
curl_setopt($curlObject,CURLOPT_URL,$fullUrl); 
curl_setopt($curlObject,CURLOPT_HEADER,false); 
curl_setopt($curlObject,CURLOPT_RETURNTRANSFER,true); 
$returnYahooWeather = curl_exec($curlObject); 
curl_close($curlObject); 
//print "here". $returnYahooWeather; 

$xmlobj=simplexml_load_string($returnYahooWeather); 

$res = $xmlobj->xpath("//yweather:condition"); 
$tmp = false; 
while(list(, $node) = each($res)) { 
    $tmp = $node; 
} 
$attribs = $tmp->attributes(); 
print "Temperature [".$attribs['temp']."]"; 
+0

謝謝你,它的工作原理,但我不明白在循環while(list($ node)= each($ res) ){..請解釋你是否不介意。 – seun 2011-06-02 15:25:32

+0

這只是我的懶惰。如果有多個'yweather:condition'元素,那麼它將遍歷它們。在這種情況下,只有1個,它只是獲得一個項目。我確信有一種方法可以在沒有這個循環的情況下完成,但是由於我的代碼在四處存在,所以速度更快。 – Femi 2011-06-02 16:01:53

2

我覺得最簡單的SimpleXML用PHP。

$xml = simplexml_load_string($returnYahooWeather); 
echo $xml->Path->To->Temperature; 

這很簡單,你可以在SimpleXML中使用XPath :)。還有其他解析XML的方法,如前面提到的DOMDocument就是其中之一。