Неопределенный префикс пространства имен при использовании API запроса погоды Yahoo

0

Продолжайте получать ошибку пространства имен при использовании кода ниже

<?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>';
    }
?>
  • 0
    Было бы неплохо узнать, как выглядит XML.
  • 0
    Примечание: измените &format=xml на &format=json а затем просто json_decode результаты и работайте с простым массивом PHP!
Показать ещё 9 комментариев
Теги:
weather
yahoo

1 ответ

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

Протестировано локально на моей машине.

  • 0
    позвольте мне попробовать это. Спасибо
  • 0
    это работает как шарм .. с помощью JSON выглядит гораздо проще

Ещё вопросы

Сообщество Overcoder
Наверх
Меню