PHP example script

This tutorial shows you how to get started using Frost in PHP. The snippets of code on this page can be put together to make your own script for extracting data.

First and most importantly, the client ID must be defined to be able to authenticate the requests.

// Insert your own client ID here
client_id = '<INSERT CLIENT ID HERE>'

In the next block of code, we build the URL and perform the request to Frost. Here we use the observations endpoint to get measured data. The three parameters sources, elements and referencetime are defined in this block as they are mandatory for the observations endpoint.

// Build the URL and define parameters
$url = "https://" . $client_id . "@frost.met.no/observations/v0.jsonld";
$url .= "?sources=" . "SN18700,SN90450";
$url .= "&elements=" . "mean(air_temperature P1D),sum(precipitation_amount P1D),mean(wind_speed P1D)";
$url .= "&referencetime=" . "2010-04-01/2010-04-03";

// Replace spaces
$url = str_replace(" ", "%20", $url);

// Extract JSON data
$response = file_get_contents($url);
$response = json_decode($response, true);

Once we have extracted the JSON from the request, we want to make sure that we actually got some data. This block can be used to ensure that data was retrieved.

if (array_key_exists('data', $response)) {
    $data = $response['data'];
    echo "Data retrieved from frost.met.no";
} else {
    echo "Error: the data retrieval was not successful!";
}

Finally, we loop through the JSON structure of the data and echo the time, weather element name and value.

// Loop through the data
foreach($data as $value) {
    $time = new DateTime($value['referenceTime']);
    $time = $time->format('Y-m-d');
    foreach($value['observations'] as $observation) {
        $element = $observation['elementId'];
        $value = $observation['value'];
        $offset = $observation['timeOffset'];
        $unit = $observation['unit'];
        
        echo $time . ': ' . $element . ' with offset ' . $offset . ' is ' . $value . ' ' . $unit;
    }
}

This code will print each measurement value out to screen. Inside of the loop, you will have access to each timestep, element name and value, and you can change this code to process them as you wish.