Ever needed to include weather on a website?
Frustrated at the crappy, ugly widgets?
No fear! Google is here!
Strictly speaking, this API is only for iGoogle. But it works, and probably always will.
Here's the XML: http://www.google.co...her=new+york,ny
Remember your XML tags reflect what you need to code in your PHP in order to pull the data you need. And you'll of course need to edit the location. You can use post codes, zip codes, Cities etc. Before you use though try the URL in your browser to make sure the big G can fetch the data.
So, if we just want the current forecast, we write this:
foreach($item->current_conditions as $new) { }For the forecast, use:
foreach($item->forecast_conditions as $new) { }Then inside those tags, you need to pull from the XML what info you want.
E.g. for temperature:
echo $new->temp_c['data'];
You can choose either Fahrenheit or Celsius. Your data won't include the C/F degree symbols, so I include the Celsius symbol using:
echo '°C';
And that's it! It's very easy to use. Any questions feel free to ask.
I changed my mind and decided to include full code as I appreciate this may be a handy opportunity for someone to learn how to parse XML.
Having said that, this is a specific example that does what I wanted, so even if you use it you'll end up changing most of it anyway.
Full Code (Example Only)
<?php
function getWeather() {
$requestAddress = "http://www.google.com/ig/api?weather=bn424nt&hl=en";
$xml_str = file_get_contents($requestAddress,0);
$xml = new SimplexmlElement($xml_str);
$count = 0;
echo '<div id="weather">';
foreach($xml->weather as $item) {
foreach($item->current_conditions as $new) {
echo '<div class="weathericon">';
echo '<img src="http://www.google.com/' . $new->icon['data'] . '"/><br/>';
echo '</div>';
echo $new->temp_c['data'];
echo '°C';
echo '<br/>';
echo $new->wind_condition['data'];
}
}
echo '</div>';
}
getWeather();
?>
This post has been edited by brightonmike: 19 October 2011 - 03:28 PM
Help
















