A few days back , we published an article about currency conversion using Google calculator API and php. Today we are going to show you how to display current weather information and forecast data using php and Google Weather API.
The API is situated at http://www.google.com/ig/api?weather and the callback URL for a specific place looks like this :
The returned data in XML form contains information such as current temperature , weather condition , humidity , winds and forecast for the next few days. The following is a simple php script which extracts the current temperature, weather condition, humidity and temperature & weather condition forecast for one day. The following example uses CURL so you must have it enabled for the code to work. ( Note : The following code displays temperature in °C )
$place="Doha";
//Initialize CURL
$ch = curl_init();
$timeout = 0;
//Set CURL options
curl_setopt ($ch, CURLOPT_URL, ‘http://www.google.com/ig/api?weather=’.$place.‘&hl=en’);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$xml_str=curl_execREMOVE($ch);
//close CURL cause we dont need it anymore
curl_close($ch);
// Parse the XML response
$xml = new SimplexmlElement($xml_str);
foreach($xml->weather as $item) {
foreach($item->current_conditions as $new) {
//For temperature in fahrenheit replace temp_c by temp_f
$current_temperature=$new->temp_c[‘data’];
$current_humidity=$new->humidity[‘data’];
}
$current_condition=$item->forecast_conditions[0]->condition[‘data’];
$next_temperature=$item->forecast_conditions[1]->high[‘data’];
//to convert Fahrenheit into Celcius
$next_temperature=round(($next_temperature-32)*(5/9));
$next_condition=$item->forecast_conditions[1]->condition[‘data’];
}
Usage
Assign the required value to the $place variable and place the code in your file. The script assigns 5 variables : $current_temperature, $current_condition, $current_humidity, $next_temperature, $next_condition which you can use as following :
Current condition : <?php echo $current_condition; ?> <br />
<?php echo $current_humidity; ?> <br />
Tomorrows temperature : <?php echo $next_temperature; ?> °C <br />
Tomorrows condition : <?php echo $next_condition; ?> <br />












[...] This post was mentioned on Twitter by GoogleAPI Services, Joseph Livingston. Joseph Livingston said: <b>Weather</b> forecast script in php using Google <b>Weather</b> API – Dynamic Guru http://bit.ly/c3E2lc [...]