HomeCoding & Programming

Show weather information with Google Weather API & PHP

Like Tweet Pin it Share Share Email

If you need to show weather in your website. A very simple way to extracting weather information of any location is via Google weather API.

The API will return weather in a very simple XML format that you can easily parse and integrate on any page.

The API need not required any key, you just simply need to pass a city name or postal code (US only), such as Jaipur, Rajasthan

 

http://www.google.com/ig/api?weather=YOURADDRESS

<?php
$xml = simplexml_load_file('http://www.google.com/ig/api?weather=YOURADDRESS');
$information = $xml->xpath("/xml_api_reply/weather/forecast_information");
$current = $xml->xpath("/xml_api_reply/weather/current_conditions");
$forecast_list = $xml->xpath("/xml_api_reply/weather/forecast_conditions");
?>

A Sample Code for Jaipur, Rajasthan


<?php

$xml = simplexml_load_file('http://www.google.com/ig/api?weather=Jaipur,Rajasthan');

$information = $xml->xpath("/xml_api_reply/weather/forecast_information");

$current = $xml->xpath("/xml_api_reply/weather/current_conditions");

$forecast_list = $xml->xpath("/xml_api_reply/weather/forecast_conditions");
?>

HTML page code


<html>
<head>
    <title>Google Weather API</title>
</head>
<body>
    <h1><?php echo $information[0]->city['data']; ?></h1>

    <h2>Today's weather</h2>
    <div> <img src="<?php echo 'http://www.google.com' . $current[0]->icon['data']?>" />
      <div> <?php echo $current[0]->temp_f['data'] ?>&deg; F, <?php echo $current[0]->condition['data']; ?> </div>
    </div>

    <h2>Forecast (Next 4 Days)</h2>
    <?php foreach ($forecast_list as $forecast) : ?>
    <div> <img src="<?php echo 'http://www.google.com' . $forecast->icon['data']?>"  />
      <div><?php echo $forecast->day_of_week['data']; ?></div>
      <div> <?php echo $forecast->low['data'] ?>&deg; F - <?php echo $forecast->high['data'] ?>&deg; F, <?php echo $forecast->condition['data']; ?> </div>
    </div>
    <?php endforeach; ?>
    
</body>
</html>


 

Weather parameters in Google’s Weather XML API
1) US or Canadian zip code (http://www.google.com/ig/api?weather=24558)
2) City,state (http://www.google.com/ig/api?weather=New York,US)

 

hl parameter (language parameter)
The default setting,if not defined,is hl=en
You can test it with French,hl=fr (i.e. google.com/ig/api?weather=24558&hl=fr)
The language code will NOT change the XML tags,only change the data in those tags.

 

You can do the temperature degrees Fahrenheit (°F) or Celsius (°C aka centigrade) calculation by the below Formula.

°C  *  9/5 + 32     = °F

(°F  –  32)  * 5/9   = °C

 

Comments (2)

Comments are closed.