I can't figure out how to make my PHP script work and I'm not allowed to use debugging tools on the server or run it locally. Please help.
It is targeting an open data API (Statistics Norway / SSB), specifically this one:
$url = "http://data.ssb.no/api/v0/no/table/08940";
The API is queried with POST and provides output according to posted message body which must be formatted as JSON.
I build the $body with a nested array in PHP, and the output of json_encode($body, JSON_PRETTY_PRINT);
is provided below (truncated).
This runs just fine in the SSB API Console as well as in Restlet Client.
{
"query": [
{
"code": "UtslpTilLuft",
"selection": {
"filter": "item",
"values": [
"1",
"2"
]
}
},
{
"code": "ContentsCode",
"selection": {
"filter": "item",
"values": [
"UtslippCO2ekvival"
]
}
},
{
"code": "Tid",
"selection": {
"filter": "item",
"values": [
"1990",
"1991"
]
}
}
],
"response": {
"format": "json"
}
}
Here is the script for the file_get_contents():
$json_body = json_encode($body);
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/json',
'content' => $json_body
)
);
$context = stream_context_create($options);
$file = file_get_contents($url, false, $context);
$output = json_decode($file, true);
I have looked at the answers given in How to post data in PHP using file_get_contents?, tried to replace json_encode() with http_build_query() and http_build_query(json_encode()), experimented with different 'header' but print_r($output) gives me nothing.
Edit: I removed $output = json_decode($file, true);
and now it prints the JSON array! Still need to figure out how to turn that into a PHP variable but how can I do that without json_decode...?
Edit 2: I figured out the data is actually not regular JSON, but JSON-STAT, in the form of a unidimensional array. The proper call in the message body (response: format) is not "json" but "json-stat". With "json", the returned data was incompatible for json_decode().
Any tips on how to parse that to a regular associative array in PHP is highly appreciated!