2013-07-13 56 views
-3

從openweathermap獲取天氣數據失敗。這裏是我的代碼:將XML數據解析爲PHP變量

$xml = new 
SimpleXMLElement(file_get_contents('http://api.openweathermap.org/data/2.5/weather?q=london&mode=xml')); 
$country = $xml->code->country; 
$city = $xml->code->city; 
echo "Country: $country<br/>City: $city"; 

當我回聲我什麼也沒有得到。幫助表示讚賞!

+2

這個問題似乎是題外話,因爲它缺乏的故障排除一個錯字基本的瞭解。 – hakre

+0

可能的重複:[如何在PHP中獲取有用的錯誤消息?](http://stackoverflow.com/q/845021/367456) – hakre

回答

3

,給國家和城市價值的正確路徑如下:

$country = $xml->city->country; 
$city = $xml->city['name']; 

您可能還需要刪除URL中的空間,所以完整的代碼看起來像:

$xml = new SimpleXMLElement(file_get_contents('http://api.openweathermap.org/data/2.5/weather?q=london&mode=xml')); 
$country = $xml->city->country; 
$city = $xml->city['name']; 
echo "Country: $country<br/>City: $city"; 

您可能想要快速查看basic SimpleXML usage

0

你丟失了所有的錯誤信息,也不是缺少繼續進一步對前檢查函數的返回值:

Warning: file_get_contents(http://api.openweathermap.org/data/2.5/weather ? q=london&mode=xml): failed to open stream: HTTP request failed! HTTP/1.1 400 BAD_REQUEST

這意味着你的HTTP請求失敗,因爲它是一個錯誤的請求。檢查URI是否正確。如果是這樣,請聯繫API服務提供商以獲取支持選項。

Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML'

您的腳本有一個致命錯誤。它不僅沒有輸出任何東西,甚至在達到計劃結束之前停下來停下來。那是因爲你認爲一切都必須始終有效。相反還要檢查錯誤消息。

這已經在這裏前一個問題作了概述: