【问题标题】:Parse XML data to a PHP variable [closed]将 XML 数据解析为 PHP 变量 [关闭]
【发布时间】:2013-07-12 02:10:39
【问题描述】:

从 openweathermap 获取天气数据失败。这是我的代码:

$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"; 

当我回显时,我什么也得不到。帮助表示赞赏!

【问题讨论】:

标签: php http weather-api openweathermap


【解决方案1】:

国家和城市值的正确路径如下:

$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

【讨论】:

    【解决方案2】:

    您错过了所有错误消息,也没有在继续下一步之前检查函数返回值:

    警告:file_get_contents(http://api.openweathermap.org/data/2.5/weather?q=london&mode=xml):打开流失败:HTTP 请求失败! HTTP/1.1 400 BAD_REQUEST

    这意味着您的 HTTP 请求失败,因为它是一个错误的请求。检查 URI 是否正确。如果是这样,请联系 API 服务提供商以获取您的支持选项。

    致命错误:未捕获的异常 'Exception' 带有消息“无法将字符串解析为 XML”

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

    这已在之前的问题中进行了概述:

    【讨论】:

      猜你喜欢
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 1970-01-01
      相关资源
      最近更新 更多