【问题标题】:How to get 5 day Yahoo weather forecast如何获得 5 天的雅虎天气预报
【发布时间】:2013-02-28 03:27:53
【问题描述】:

我一直在为我的网站制作天气提要。

我目前只能获得未来 2 天的预报。我想要未来 5 天的预测。

这是我的代码:

$ipaddress = $_SERVER['REMOTE_ADDR'];
$locationstr = "http://api.locatorhq.com/?user=MYAPIUSER&key=MYAPIKEY&ip=".$ipaddress."&format=xml";

$xml = simplexml_load_file($locationstr);

$city = $xml->city;

switch ($city)
{
    case "Pretoria":
        $loccode = "SFXX0044";

        $weatherfeed = file_get_contents("http://weather.yahooapis.com/forecastrss?p=".$loccode."&u=c");
        if (!$weatherfeed) die("weather check failed, check feed URL");
        $weather = simplexml_load_string($weatherfeed);

        readWeather($loccode);
        break;
}

function readWeather($loccode)
{
    $doc = new DOMDocument();
    $doc->load("http://weather.yahooapis.com/forecastrss?p=".$loccode."&u=c");

    $channel = $doc->getElementsByTagName("channel");

    $arr;
    foreach($channel as $ch)
    {
        $item = $ch->getElementsByTagName("item");
        foreach($item as $rcvd)
        {
            $desc = $rcvd->getElementsByTagName("description");

            $_SESSION["weather"] = $desc->item(0)->nodeValue;
        }
    }
}

我想请您注意查询天气的行:

$doc = new DOMDocument();
$doc->load("http://weather.yahooapis.com/forecastrss?p=".$loccode."&u=c");

// url resolves to http://weather.yahooapis.com/forecastrss?p=SFXX0044&u=c in this case

搜索谷歌,我发现this link 建议我改用这个网址:

$doc->load("http://xml.weather.yahoo.com/forecastrss/SFXX0044_c.xml");

虽然这也有效,并且我在 XML 文件中看到了 5 天的预测,但我仍然在我的网站上看到了 2 天的预测。

我感觉这是因为我利用了 RSS 提要中的 channel 子元素,而 XML 提要没有这样的子元素。

如果有人能在这里提供任何见解,我将不胜感激。

【问题讨论】:

  • 你为什么用SimpleXML加载它,而不是用它,然后用DOMDocument再次加载它?我个人觉得SimpleXML 更容易解析 RSS 提要,但无论哪种方式,您都应该使用其中一种。

标签: php xml rss yahoo-weather-api


【解决方案1】:

这就是我过早提问的结果...

当我再次查看我的代码时,我注意到我两次引用了 yahooapis URL:一次在 switch 中,另一次在 readWeather 中。

根据提到的线程删除了多余的引用并更新了 url,我发现它现在可以工作了。

查看更新的代码以供参考:

switch ($city)
{
    case "Pretoria":
        $loccode = "SFXX0044";

        readWeather($loccode);
        break;
}

function readWeather($loccode)
{
    $doc = new DOMDocument();
    $doc->load("http://xml.weather.yahoo.com/forecastrss/".$loccode."_c.xml");

    $channel = $doc->getElementsByTagName("channel");

    $arr;
    foreach($channel as $ch)
    {
        $item = $ch->getElementsByTagName("item");
        foreach($item as $rcvd)
        {
            $desc = $rcvd->getElementsByTagName("description");

            $_SESSION["weather"] = $desc->item(0)->nodeValue;
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-09
    • 2014-11-20
    • 1970-01-01
    • 2011-11-15
    • 2013-10-25
    • 2018-09-17
    • 2014-05-13
    • 1970-01-01
    相关资源
    最近更新 更多