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

Undefined namespace prefix when using yahoo weather query api

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

<?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>';
    }
?>

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

在我的机器上本地测试。