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.

Full PHP sample code

Full sample code for this sample can be found on our GitHub repository at: https://github.com/visualcrossing/WeatherApi/blob/master/PHP/weather-api-sample-timeline.php

Steps to retrieve weather data in PHP

There are five 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]));
	//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);
	parse_str($query_str, $query_params);
	//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/timeline/{$location}?unitGroup={$unitGroup}&key={$apiKey}&contentType=json";

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.

$response_data = json_decode($json_data);

$resolvedAddress=$response_data->resolvedAddress;
$days=$response_data->days;

Step five – Use the data

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

<h1>Weather Forecast for <?php echo $resolvedAddress; ?></h1>
<table>
  <tr><th>datetime</th><th>tempmax</th><th>tempmin</th><th>precip</th><th>windspeed</th><th>windgust</th><th>cloudcover</th></tr>
  <?php
  foreach ($days as $day) {
  ?>
  <tr>
    <td><?php echo $day->datetime; ?></td>
    <td><?php echo $day->tempmax; ?></td>
    <td><?php echo $day->tempmin; ?></td>
    <td><?php echo $day->precip; ?></td>
    <td><?php echo $day->windspeed; ?></td>
    <td><?php echo $day->windgust; ?></td>
    <td><?php echo $day->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.

if ($startDateTime!=null ) {
  $api_url= $api_url="https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/{$location}/{$startDateTime}/{$endDateTime}?unitGroup={$unitGroup}&key={$apiKey}&contentType=json";
} else {
   $api_url= $api_url="https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/{$location}/last7days?unitGroup={$unitGroup}&key={$apiKey}&contentType=json";
}

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);

$resolvedAddress=$response_data->resolvedAddress;
$days=$response_data->days;

Step five – Use the data

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

<?php
foreach ($days as $day) {
?>
<tr>
 <td><?php echo $day->datetime; ?></td>
 <td><?php echo $day->tempmax; ?></td>
 <td><?php echo $day->tempmin; ?></td>
 <td><?php echo $day->precip; ?></td>
 <td><?php echo $day->windspeed; ?></td>
 <td><?php echo $day->windgust; ?></td>
 <td><?php echo $day->cloudcover; ?></td>
</tr>
<?php } ?>
</table>

Questions or need help?

If you have a question or need help, please post on our actively monitored forum for the fastest replies. You can also contact us via our support site or drop us an email at support@visualcrossing.com.

2 thoughts on “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

Comments are closed.

Scroll to Top
This site is registered on wpml.org as a development site. Switch to a production site key to remove this banner.