Parse Yahoo Weather Data With PHP
The Yahoo! Developer Network offers all sorts of excellent APIs, RSS feeds and other resources for web developers. I’ve written in the past about using their stock quote CSV files to get stock updates and today I’ll show you a really short piece of code to gather weather data directly from Yahoo! Weather.
The code below is pretty simple but it relies on Magpie to handle the RSS stuff. I’ve written about Magpie before if you’re interested in learning more. The trick with these weather feeds from Yahoo! is stripping out the current weather and the forecast from between the bizarre HTML markup they’ve put around it all. This chunk of code should take care of that for you.
<?php
include("rss_fetch.inc");
$zipcode = "44101";
$feed = fetch_rss("http://xml.weather.yahoo.com/forecastrss?p=".$zipcode);
if ($feed and !$feed->ERROR)
{
$items = array_slice($feed->items, 0);
foreach ($items as $item)
{
$arr_weather = explode('<br />', str_replace('<BR />', '<br />', str_replace('<p />', '<br />', $item['description'])));
$arr_forecast = explode('-', $arr_weather[5]);
$current_weather = trim($arr_weather[2]);
$forecast_weather = trim($arr_forecast[1]);
}
}
?>
When this is done you’re left with a variable named $current_weather that contains the weather as it exists at that moment and another variable named $forecast_weather with the current day’s weather forecast.
I’ve used this chunk of code severals times on intranets I’ve built. A variation on this code that includes weather icons helps power some features at Fore Score Golf Stats as well. A big use there is to show the current weather at any courses a user has played at (seen on the right).
If you want to read some more about Yahoo’s weather RSS feeds then check out the weather section of their Developer Network.




Thats a great Idea. While i’m not so concerned about the weather - this same idea and technology can be used to do a lot more with other RSS feeds.
Comment by Matt Ellsworth — January 12, 2008 @ 8:39 pm