Get weather information using php

Most of webmasters want to display weather information on their website. So I have decided to provide a tutorial to do this via PHP script.
There are tones of APIs that provides weather information like Yahoo weather, Open Weather Map, Accuweather, etc but my favourite is Open Weather Map. Lets start with OpenWeatherMap API.

Get current weather forecast

By City Name

Pass city name and two digit country code in query parameter `q` eg:
api.openweathermap.org/data/2.5/weather?q=London,uk

By Geographic Coordinats

Pass latitude `lat` and longitude `lon` of your location eg:
api.openweathermap.org/data/2.5/weather?lat=35&lon=139

Response in JSON format

{"coord":{"lon":-0.13,"lat":51.51},"sys":{"message":0.046,"country":"GB","sunrise":1402371809,"sunset":1402431395},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01d"}],"base":"cmc stations","main":{"temp":287.58,"pressure":1016,"humidity":77,"temp_min":286.15,"temp_max":289.15},"wind":{"speed":2.6,"deg":260},"rain":{"3h":0},"clouds":{"all":0},"dt":1402377600,"id":2643743,"name":"London","cod":200}

Parameters description

Parameter Description Using
id City identification mandatory
dt Time of data receiving in unixtime GMT mandatory
coord.lat coord.lng City location mandatory
name City name mandatory
main.temp Temperature in Kelvin. Subtracted 273.15 from this figure to convert to Celsius. mandatory
main.humidity Humidity in % mandatory
main.temp_min main.temp_max Minimum and maximum temperature Optional
main.pressure Atmospheric pressure in hPa mandatory
wind.speed Wind speed in mps mandatory
wind.deg Wind direction in degrees (meteorological) mandatory
clouds.all Cloudiness in % mandatory
weather weather condition More about data Weather Condition Codes Optional
rain.3h Precipitation volume mm per 3 hours Optional
snow.3h Precipitation volume mm per 3 hours Optional

Getting weather information using php

  <?php
  $city="Delhi";
  $country="IN"; //Two digit country code
  $url="http://api.openweathermap.org/data/2.5/weather?q=".$city.",".$country."&units=metric&cnt=7&lang=en";
  $json=file_get_contents($url);
  $data=json_decode($json,true);
  //Get current Temperature in Celsius
  echo $data['main']['temp']."<br>";
  //Get weather condition
  echo $data['weather'][0]['main']."<br>";
  //Get cloud percentage
  echo $data['clouds']['all']."<br>";
  //Get wind speed
  echo $data['wind']['speed']."<br>";
  ?>

Liked It? Get Free updates in your Email

Delivered by feedburner

2 thoughts on “Get weather information using php

  1. ud
    #

    Hi Thank You for your information. But how can i display the weather status icon using above php example ?
    -thanks

    Reply

Leave a Reply

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