BackendGuy
Forecast weather using OpenWeatherMap with PHP

Forecast weather using Openweather Api in PHP

In this tutorial, we are going to create a PHP application to display weather forecast information using an API. I have used OpenWeatherMap service to implement this with PHP. We will just grab the weather information provided by the API and display it in the application.

This is one of the best API service that provides weather forecast. It provides tremendous volume of weather data regularly. It is a free service with limited access. For basic usage, it should be sufficient and for advanced you may have to pay for it. Integrating this API with a PHP application is easy. The following three steps are used for the integration.

  1. Get API key
  2. Locate city id
  3. Request weather forecast by sending API key and city id

Get OpenWeatherMap API key

  1. To get the API key, we need to register with OpenWeatherMap. After signing up, it will redirect us to the profile settings.
  2. Above the profile settings form, there is a top menu containing several tabs. Click the API keys tab and copy the API key. This will be later used to request API for the weather forecasts.

signup-to-get-api-key

Locate city id

By clicking the below link, the cities list will be downloaded in a compressed format. Unzip the file and get the id of the city/state.

http://bulk.openweathermap.org/sample/city.list.json.gz

After unzipping, the file will have the JSON formatted data containing an array of locations. Each array item contains the geodata like latitude, longitude, country, city/state, city id.

PHP Code to Request Weather Forecast by sending keys

This is the PHP code to request the OpenWeatherMap service to get the weather forecasts. While sending the request, the API key and the city id is sent with request URL query string.

I used PHP CURL to send the API request. The CURL response will be in a JSON format. By decoding the JSON response, we can get the weather data and populate it in the browser.

<?php
$apiKey = "API KEY";
$cityId = "CITY ID";
$googleApiUrl = "http://api.openweathermap.org/data/2.5/weather?id=" . $cityId . "&lang=en&units=metric&APPID=" . $apiKey;

$ch = curl_init();

curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $googleApiUrl);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);

curl_close($ch);
$data = json_decode($response);
$currentTime = time();
?>

HTML Code to Show Weather Forecasts

This HTML code is used to display the weather forecast by decoding the JSON object response. In this section, we access the location, weather description, icon, min-max ranges of the temperature, humidity and wind speed.

<!doctype html>
<html>
<head>
<title>Forecast Weather using OpenWeatherMap with PHP</title>
</head>
<body>
    <div class="report-container">
        <h2><?php echo $data->name; ?> Weather Status</h2>
        <div class="time">
            <div><?php echo date("l g:i a", $currentTime); ?></div>
            <div><?php echo date("jS F, Y",$currentTime); ?></div>
            <div><?php echo ucwords($data->weather[0]->description); ?></div>
        </div>
        <div class="weather-forecast">
            <img
                src="http://openweathermap.org/img/w/<?php echo $data->weather[0]->icon; ?>.png"
                class="weather-icon" /> <?php echo $data->main->temp_max; ?>°C<span
                class="min-temperature"><?php echo $data->main->temp_min; ?>°C</span>
        </div>
        <div class="time">
            <div>Humidity: <?php echo $data->main->humidity; ?> %</div>
            <div>Wind: <?php echo $data->wind->speed; ?> km/h</div>
        </div>
    </div>
</body>
</html>

Output of Weather Forecast using OpenWeatherMap with PHP

This is the output of the example program we have seen above. It provides weather information by decoding the JSON response of the API.

forecast-weather-using-openweathermap-with-php-output

BackendGuy

1 comment

  • Hi there,

    I came across your website and wanted to get in touch.

    I run an animation studio that produces animated explainer videos helping companies to explain what they do, why it matters and how they’re unique in less than 2 minutes.

    Here are some examples of our work:
    http://www.bit.ly/animationworks – pretty good right?

    I wanted to reach out to hear if the idea of an animated explainer video is something you’ve ever thought about creating and could be interested in exploring further?

    We have a proven production process and handle everything needed for a quality video that typically takes us 6 weeks to produce from start to finish.

    First, we nail the script, design storyboards you can’t wait to see animated. Voice actors that capture your brand and animation that screams premium with sound design that brings it all together.

    Our videos are made from scratch and designed to make you stand out and get results. No templates, no cookie cutter animation that tarnishes your brand.

    If you’re interested in learning more, please contact us on the email below:
    Email: storybitestudios@gmail.com

    Thank you for your attention.

Your Header Sidebar area is currently empty. Hurry up and add some widgets.