使用yahoo weather query api时未定义的名称空间前缀

时间:2015-03-12 13:06:29

标签: php api yahoo weather

使用下面的代码

时不断出现名称空间错误
<?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>';
    }
?>

1 个答案:

答案 0 :(得分:0)

根据要求,这是使用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>';
}

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