How to load weather data in PHP

If you are creating web pages or other applications using PHP, then you may find the need to include weather data directly on your page. When incorporating weather data, you can use a pre-built widget or maybe even a WordPress plugin, however if you want full control over how the data is retrieved and displayed, you may want to request the data when rendering the page on the server. If you render the data on the server, the data is available immediately after the page is rendered on the browser.

In this article, we describe how to use the Weather API to retrieve weather data directly within PHP script. After retrieving the data in JSON format, we will parse the data and display the data as a simple HTML table.

If you would like the follow along with the steps below, you will need an API key. You can get one for free by signing up. For more information, see how to sign up for a weather API key.

The sample code described in this article is available on our GitHub:

https://github.com/visualcrossing/WeatherApi/blob/master/PHP/weather-api-sample.php

Steps to retrieve weather data in PHP

There are five simple steps to retrieving the weather data via a weather API in PHP:

Step one – Set up the parameters for the request.

For a weather forecast request, this is as simple as the location being requested and the units to use. For a historical weather request, we also need to include the date range.

Step two- Create the Weather API request

The weather API request is a GET or POST HTTPS request. We can create the request from the parameters gathered in step one by string concatenation.

Step three – Submit the request

From step two, we submit the request to retrieve the result.

Step four – Parse the response

The weather data response is returned in CSV or JSON format. In this article, we are going to use the JSON response by parsing the string JSON response into a JSON object instance.

Step five – Use the data

We now have the weather data, and we can use this data to do something useful. We will render a simple HTML table using the data but that is just the beginning. You could use the weather data for data science, processing, or any kind of complex charts. We use the same PHP techniques described in this page to construct our Weather History page.

Retrieving weather forecast data using PHP

Step one – Set up the parameters for the request

The following code reads the parameters from the request:

//helper method to retrieve data from the URL path or query string
 function extractParam($pathSegments, $pathIndex, $query_params, $query_param) {
   if (count($pathSegments)>$pathIndex) return trim(urldecode($pathSegments[$pathIndex]));
   if ($query_params[$query_param]!=null) return trim(urldecode($query_params[$query_param]));
   return null;
 }

 $segments = explode('/', trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/'));
 $query_str = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);

//the location for the weather data (an address or partial address)
 $location=extractParam($segments,1, $query_params, "location");

// the unit group - us, metric or uk
 $unitGroup=extractParam($segments,2, $query_params, "unitGroup");

//we want weather data to aggregated to daily details.
 $aggregateHours=24;
//your API key
 $apiKey="YOUR_API_KEY";

Step two- Create the Weather API request

We now create the Weather API request using these parameters. For a weather forecast, we simply have the location, unit group type and our API key. If you would like help building weather API queries such as these, the Weather Data Services page will create the API requests for you. See our Getting started Guide to get started quickly.

$api_url="https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata"
   "/forecast?unitGroup{$unitGroup}&aggregateHours{$aggregateHours}".
    "&location={$location}&key={$apiKey}
    &contentType=json&locationMode=single";
 
$json_data = file_get_contents($api_url);

Step three – Submit the request

In our sample, we use the simple ‘file_get_contents’ PHP method to submit the Weather API request to the the server. Other HTTP libraries may be more appropriate in your case if you want to handle security, proxies etc.

$json_data = file_get_contents($api_url);

Step four – Parse the response

We now have a string named ‘$json_data’ that contains our weather data. We can parse this into a JSON object. We can then read the location information from the JSON as $locationInstance and then read the array of weather data from the location. See Weather API JSON for more information about the JSON structure.

$response_data = json_decode($json_data);

$locationInstance=$response_data->location;
$values=$locationInstance->values;

Step five – Use the data

We now use the weather data to render a simple HTML table:

<h1>Weather Forecast for <?php echo $locationInstance->address; ?></h1> <table>
<tr><th>Date</th><th>Max Temp</th><th>Min Temp</th><th>Precip</th><th>Wspd</th><th>Wgust</th><th>Cloud cover</th></tr>
<?php
foreach ($values as $value) {
?>
<tr>
 <td><?php echo $value->datetimeStr; ?></td>
 <td><?php echo $value->maxt; ?></td>
 <td><?php echo $value->mint; ?></td>
 <td><?php echo $value->precip; ?></td>
 <td><?php echo $value->wspd; ?></td>
 <td><?php echo $value->wgust; ?></td>
 <td><?php echo $value->cloudcover; ?></td>
</tr>
<?php } ?>
</table>

Retrieving historical weather data using PHP

Retrieving the historical weather data is very similar to retrieving the weather forecast. The main difference is that we also need to include the time information for the historical weather data we are requesting.

Step one – Set up the parameters for the request

The following code reads the parameters from the request. In this case we also include the startDateTime and endDateTime to indicate the historical date range.

//helper method to retrieve data from the URL path or query string
 function extractParam($pathSegments, $pathIndex, $query_params, $query_param) {
   if (count($pathSegments)>$pathIndex) return trim(urldecode($pathSegments[$pathIndex]));
   if ($query_params[$query_param]!=null) return trim(urldecode($query_params[$query_param]));
   return null;
 }

 $segments = explode('/', trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/'));
 $query_str = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);

//the location for the weather data (an address or partial address)
 $location=extractParam($segments,1, $query_params, "location");

// the unit group - us, metric or uk
 $unitGroup=extractParam($segments,2, $query_params, "unitGroup");

//the start and and end date for the data in2019-06-13T00:00:00format
$startDateTime=extractParam($segments,3, $query_params, "fromdate");

$endDateTime=extractParam($segments,4, $query_params, "todate");

//we want weather data to aggregated to daily details.
 $aggregateHours=24;
//your API key
 $apiKey="YOUR_API_KEY";

Step two- Create the Weather API request

We next create the Weather API request using these parameters. Notice that is have to include starting and ending information since this is a history query. As with forecast, if you would like help building weather API queries such as these, the Weather Data Services page will create the API requests for you.

$api_url="https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/history?"
     unitGroup={$unitGroup}&aggregateHours={$aggregateHours}".
                 "&location={$location}&key={$apiKey}
&collectStationContribution=true&contentType=json&locationMode=single";

if ($startDateTime!=null ) {
  $api_url=$api_url.
     "&startDateTime={$startDateTime}&endDateTime={$endDateTime}";
} else {
  $api_url=$api_url."&period=last7days";
}

Step three – Submit the request

Again we use the file_get_contents to retrieve the weather data in this simple sample.

$json_data = file_get_contents($api_url);

Step four – Parse the response

In this example ‘$json_data’ is our string of weather data. We now parse this into a JSON object. We can then read the location information from the JSON as $locationInstance and then read the array of weather data from the location. See Weather API JSON for more information about the JSON structure.

$response_data = json_decode($json_data);

$locationInstance=$response_data->location;
$values=$locationInstance->values;

Step five – Use the data

We now use the above weather data to render a simple HTML table:

<h1>Weather History for <?php echo $locationInstance->address; ?></h1> <table>
<tr><th>Date</th><th>Max Temp</th><th>Min Temp</th><th>Precip</th><th>Wspd</th><th>Wgust</th><th>Cloud cover</th></tr>
<?php
foreach ($values as $value) {
?>
<tr>
 <td><?php echo $value->datetimeStr; ?></td>
 <td><?php echo $value->maxt; ?></td>
 <td><?php echo $value->mint; ?></td>
 <td><?php echo $value->precip; ?></td>
 <td><?php echo $value->wspd; ?></td>
 <td><?php echo $value->wgust; ?></td>
 <td><?php echo $value->cloudcover; ?></td>
</tr>
<?php } ?>
</table>

2 Replies to “How to load weather data in PHP”

    1. Thank you for your question. This is likely because you need to encode the parameters of the request. For example replace ‘,’ in the URl with ‘%2C’ (see https://www.w3schools.com/tags/ref_urlencode.ASP). This ensures that the parameters can be sent successfully via HTTP request.

      We will change the sample code to reflect this. In the meantime, you can encode the parameters with the following code:

      $location=urlencode(trim($location));

      Place this before the the line that builds the URL.

      Thanks
      Visual Crossing Support

Leave a Reply

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