Parse Yahoo Weather Data XML with PHP

I’ve looked at parsing weather data with PHP before, but I’ve found that using Yahoo’s weather service it more stable and flexible. Luckily PHP has some excellent built in functions to parse complex XML.

First, let’s look at the code. Below is a complete weather XML parsing function that allows you to call the current temperature (or other weather information) using a zip code.

<?php
channel->item->children("http://xml.weather.yahoo.com/ns/rss/1.0");
 
foreach($items as $x => $item) {
	foreach($item->attributes() as $k => $attr) {
		if($k == 'day') $day = $attr;
		if($x == 'forecast') {
			$forecast[$x][$day . ''][$k] = $attr;
		} else {
			$forecast[$x][$k] = $attr;
		}
	}
}
 
if(isset($forecast)) {
	return $forecast['condition']['temp'];
} else {
	return "Weather for that zip code is unavailable.";
}
 
echo weather("83642");
?>

What Is All This?

All this code is actually pretty easy to understand. Lines three and four of the function are simplexml commands that load some XML for us to work with. For more information about simplexml, dig around on PHP’s website.

Now, right after we load the XML, we need to break the XML into workable pieces, which is done on line 9. Now, if you look at the raw XML supplied from Yahoo, you’ll notice that the current temperature is actually an attribute of an XML tag. So, in lines 15 through 19, we use PHP to build an array of the XML items (defined by the tag) and their attributes, out of which we return the current temperature on line 21.

So, once the data is parsed, you should be able to call back information you want, like the forecast. Try returning something like this on line 21, making sure you grab the right day:

$forecast['forecast']['Thu']['text'];

That’s It

Now, have fun with this. Add weather info wherever you want!


Add Your Comment