【发布时间】: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