首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用雅虎天气查询api时未定义的命名空间前缀

使用雅虎天气查询api时未定义的命名空间前缀
EN

Stack Overflow用户
提问于 2015-03-12 13:06:28
回答 1查看 254关注 0票数 0

使用以下代码时继续获取命名空间错误

代码语言:javascript
复制
<?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>';
    }
?>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-12 13:21:54

按照要求,这里有一个使用JSON而不是XML的解决方案:

代码语言:javascript
复制
$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>';
}

在我的机器上进行了本地测试。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29010647

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档