Weather forecast script in php using Google Weather API

Update:

This method no longer works since google now no longer allows public access to this api.
Use the following JSON weather API instead:
Weather forecast using javascript and worldweatheronline.com free api

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 :

www.google.com/ig/api?weather=PlaceName&hl=en

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 )

//Name of your town/city
$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 temperature :  &degC 
Current condition :

Tomorrows temperature : &degC
Tomorrows condition :

4 responses to this entry

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

2018 All rights reserved | Powered by WordPress
Back to top
Theme by dynamicguru.com