【问题标题】:Undefined namespace prefix when using yahoo weather query api使用 yahoo 天气查询 api 时未定义的命名空间前缀
【发布时间】:2015-03-12 13:06:28
【问题描述】:

使用以下代码时不断出现命名空间错误

<?php

    // error_reporting(0);

    $BASE_URL = "http://query.yahooapis.com/v1/public/yql";

    $yql_query = 'select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="austin, tx")';
    $result = file_get_contents($BASE_URL . "?q=" . urlencode($yql_query) . "&format=xml");

    if ($result == true) {
        $xml = simplexml_load_string($result);
        $xml->registerXPathNamespace('yweather', 'http://xml.weather.yahoo.com/ns/rss/1.0');
        $location = $xml->results->channel;

        if(!empty($location)){
            foreach($xml->results->channel->item as $item){
                $current = $item->xpath('yweather:condition');
                $temp = $current['temp'];

                echo $temp;
            }
        }
        else{
            echo '<h1>No weather for today</h1>';
        }
    }else{
        echo '<p>Weather service is down</p>';
    }
?>

【问题讨论】:

  • 很高兴知道 xml 的样子。
  • 旁注:将&amp;format=xml 更改为&amp;format=json,然后只更改json_decode 结果并使用简单的PHP 数组!
  • 那是因为你可能在错误的命名空间中。在文件的最顶部定义您正在使用的命名空间,或包含此脚本需要运行的文件(包括名称空间)。
  • 无法粘贴xml..使用url查看xml query.yahooapis.com/v1/public/…
  • @jszobody 你介意展示和举例吗?

标签: php api yahoo weather


【解决方案1】:

根据要求,这是一个使用 JSON 而不是 XML 的解决方案:

$BASE_URL = "http://query.yahooapis.com/v1/public/yql";

$yql_query = 'select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="austin, tx")';
$result = json_decode(file_get_contents($BASE_URL . "?q=" . urlencode($yql_query) . "&format=json"), true);

if(is_array($result)) {
    $location = $result['query']['results']['channel'];

    if(!empty($location)) {
        $temp = $result['query']['results']['channel']['item']['condition']['temp'];
        echo $temp;
    } else {
        echo '<h1>No weather for today</h1>';
    }
} else {
    echo '<p>Weather service is down</p>';
}

在我的机器上本地测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 2011-06-09
    • 1970-01-01
    相关资源
    最近更新 更多