NCDC Web Services weather data with REST and PHP

Tags: , , , ,



I am trying to read precipitation data from the National Climatic Data Center’s online web services with PHP, but I can’t figure out how to read it. The documentation says that it is a RESTful web service. I have gotten a token, and I have tried everything I can think of and searched the web for any suggestions I could find, but I can’t get it to return anything. My first step is to use the web service to request a list of datasets, so I know what dataset to use when I request the actual data. Here is the code I have been using to try to request the datasets. Can anybody steer me in the right direction to read the results.

$url = "https://www.ncdc.noaa.gov/cdo-web/api/v2/datasets?stationid=COOP:010957";
$curl_post_data = array("token" => $token);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_HTTPHEADER,array('Content-type: application/json','Content-length: '.strlen($curl_post_data)));
$curl_response = curl_exec($curl);
curl_close($curl);
$json_a = json_decode($curl_response,TRUE);
var_dump($json_a); // just to see the structure.
echo "n";
foreach($json_a as $row){
   echo $row->status;
   echo "n";
}   

Answer

It turns out that API V2, which the above link describes, has been deprecated, and they reverted to API V1. Too bad they didn’t bother to remove the V2 documentation from the web. V1 does not require a token, so the data retrieval is very easy (after you figure out the correct station IDs and Datasets). Here is my new code that works:

$string = file_get_contents("https://www.ncei.noaa.gov/access/services/data/v1?dataset=local-climatological-data&stations=72509014739&units=standard&startDate=2020-02-01&endDate=2020-02-12&format=json");
$json_a = json_decode($string, TRUE);
foreach($json_a as $item){
    echo $item['DATE'] . " " . $item['HourlyDryBulbTemperature'] . "F, " . $item['HourlyPrecipitation'] . "in</br>";
}


Source: stackoverflow