如何获得5天雅虎天气预报
问题描述:
我一直在为我的网站工作天气信息。如何获得5天雅虎天气预报
我目前只能够得到未来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");
虽然这也有效,我看到一个5天的预测在t他的XML文件,我仍然只看到我的网站上2天的预测。
我有一种感觉,这是因为我利用在RSS提要中找到的channel
子元素,而XML提要没有这样的子元素。
如果有人能提供任何见解,我会非常感激。
答
这是我得到提问的太早......
当我正在寻找在我的代码再次,我注意到,我有yahooapis URL引用了两次:一次是在开关,并再次在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;
}
}
}
你为什么与'SimpleXML',不使用它加载它,然后用'DOMDocument'再次加载呢?就我个人而言,我觉得'SimpleXML'对解析RSS提要比较容易,但是您应该使用其中一种。 – Cfreak 2013-03-12 14:43:50