DEV Community

HMA WebDesign
HMA WebDesign

Posted on

How to Create Weather App in PHP | OpenWeatherMap API

In this article, you will learn How to Create Weather App in PHP and How to Use OpenWeatherMap API Using PHP. Some websites required a weather app to display the current weather conditions to their users.

We are going to create a weather web application by using a weather API provided by OpenWeatherMap using PHP. By using open weather API, you can get minute weather forecasts, historical data, current state, and from short-term to annual and forecasted weather data.

Steps to Create Weather App in PHP

  1. Create the basic application front Page using HTML and CSS: I have created a basic UI that look like cards and each card displays current location weather information.
  2. Get a Weather API key using the Open Weather Map Website: You first need to Sign Up before you can generate an API key for your Weather API. After signing up navigate to the API section of the website and select the automatically generated weather API key. Save this API key as you will need this to call from your app. Open Weather Website: https://openweathermap.org/
  3. Call the weather API using PHP: I have used Retrofit for a type-safe HTTP client call. For calling the weather API we need the base URL and the user’s coordinates are parameters.

Video Tutorial (Create Weather App in PHP)

Source Code to Create Weather App in PHP

Following are the Source codes to create a Weather Application in PHP.

HTML Source Code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">

  <title>Weather App</title>
</head>
<body>
    <div class="container">

          <h1>What's The Weather?</h1>



          <form>
  <fieldset class="form-group">
    <label for="city">Enter the name of a city.</label>
    <input type="text" class="form-control" name="city" id="city" placeholder="Eg. London, Tokyo" value = "<?php echo $_GET['city']; ?>">
  </fieldset>

  <button type="submit" class="btn btn-primary">Submit</button>
</form>

          <div id="weather"><?php

              if ($weather) {

                  echo '<div class="alert alert-success" role="alert">
  '.$weather.'
</div>';

              } else if ($error) {

                  echo '<div class="alert alert-danger" role="alert">
  '.$error.'
</div>';

              }

              ?></div>
      </div>

    <!-- jQuery first, then Bootstrap JS. -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js" integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7" crossorigin="anonymous"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS Source Code

html { 
          background: url(background.jpeg) no-repeat center center fixed; 
          -webkit-background-size: cover;
          -moz-background-size: cover;
          -o-background-size: cover;
          background-size: cover;
          }

          body {

              background: none;

          }

          .container {

              text-align: center;
              margin-top: 100px;
              width: 450px;

          }

          input {

              margin: 20px 0;

          }

          #weather {

              margin-top:15px;

          }
Enter fullscreen mode Exit fullscreen mode

PHP Source Code

<?php

    $weather = "";
    $error = "";

    if ($_GET['city']) {

     $urlContents = file_get_contents("http://api.openweathermap.org/data/2.5/weather?q=".urlencode($_GET['city']).",uk&appid=4b6cbadba309b7554491c5dc66401886");

        $weatherArray = json_decode($urlContents, true);

        if ($weatherArray['cod'] == 200) {

            $weather = "The weather in ".$_GET['city']." is currently '".$weatherArray['weather'][0]['description']."'. ";

            $tempInCelcius = intval($weatherArray['main']['temp'] - 273);

            $weather .= " The temperature is ".$tempInCelcius."&deg;C and the wind speed is ".$weatherArray['wind']['speed']."m/s.";

        } else {

            $error = "Could not find city - please try again.";

        }

    }

?>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)