2013-07-13 55 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'

您的脚本有一个致命错误。它不仅没有输出任何东西,甚至在达到计划结束之前停下来停下来。那是因为你认为一切都必须始终有效。相反还要检查错误消息。

这已经在这里前一个问题作了概述: