Every web designer has at one point or another been asked, "How can I get weather on my site?" The old answer was to have a giant ugly weather channel gadget. Something that looked very nasty and you couldn't un-brand it no matter what. Some used an iframe to display external data and have it appear to be on their site. Lastly you could always just have a link that says 'click here for weather'. My goal was to get weather data from an external source and be able to customize how it looks. Fortunately now there are some great resources out there. I'm going with one that is my favorite, something extremely easy to use and customize - Google's Weather API.
To start lets pull up the URL in your browser.
If you look in the address you can see the location - New York, NY. Easy enough, let's take a look at the output.
Weather XML Output
<xml_api_reply version="1">
<weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" >
<forecast_information>
<city data="New York, NY"/>
<postal_code data="new york,ny"/>
<latitude_e6 data=" "/>
<longitude_e6 data=" "/>
<forecast_date data="2009-08-02"/>
<current_date_time data="2009-08-02 12:19:00 +0000"/>
<unit_system data="US"/>
</forecast_information>
<current_conditions>
<condition data="Light rain"/>
<temp_f data="72"/>
<temp_c data="22"/>
<humidity data="Humidity: 94%"/>
<icon data="/ig/images/weather/mist.gif"/>
<wind_condition data="Wind: N at 6 mph"/>
</current_conditions>
</weather>
</xml_api_reply>
Wow check out how easy that was. Now all we did was submit the location and hit enter. Now we have in XML weather data for that area. No advertisements and since the data is in XML we can make it look however we want. Note: I shortened the output to only one day. So what's next? Well in my case I used a PHP script to output this data. Let's take a look at that source code.
PHP Source
<?php
function getWeather() {
$requestAddress = "http://www.google.com/ig/api?weather=21619&hl=en";
// Downloads weather data based on location - I used my zip code.
$xml_str = file_get_contents($requestAddress,0);
// Parses XML
$xml = new SimplexmlElement($xml_str);
// Loops XML
$count = 0;
echo '<div id="weather">';
foreach($xml->weather as $item) {
foreach($item->forecast_conditions as $new) {
echo '<div class="weatherIcon">';
echo '<img src="http://www.google.com/' .$new->icon['data'] . '"/><br/>';
echo $new->day_of_week['data'];
echo '</div>';
}
}
echo '</div>';
}
getWeather();
?>
Stumble It