I'm trying to pull crypto-mining data from the server's API; however, when I run the .php
file, it comes back with null:
HTML/PHP
$meow_base_data = json_decode(file_get_contents($meow_base_api), true);
var_dump($meow_base_data);
var_dump
only says "NULL" - no other information.
The script for this I'm using is:
$fgc = file_get_contents($meow_base_api);
var_dump($fgc);
CodePudding user response:
When json_decode()
returns NULL
and you're sure you're getting a response, the first debugging step should be to look at what you're passing into the function.
So if the result for $meow_base_data = json_decode(file_get_contents($meow_base_api), true);
is NULL
, see what you're actually getting by running var_dump(file_get_contents($meow_base_api));
.
In your case, the result of this appears to be binary data. The clue as to what sort of data this is, is in the response headers:
Content-Type: application/json
but combined with content-encoding: gzip
. So you're getting a Gzip'ed JSON response. You need to un-gzip the response before you can pass it through json_decode()
.
Unfortunately, this is not as straightforward as it sounds. Although PHP does come with several functions to decompress Gzip-data (gzdecode()
, gzinflate()
, gzuncompress()
and zlib_decode()
), it is usually a case of trial-and-error before you find the one you need to use.
Sometimes, none of these functions are able to decompress the data out of the box. This can happen if the server uses a specific method of compression that browsers understand natively but PHP's functions don't. In this case, there will be a 10-byte prefix and an 8-byte suffix to the compressed data, so you can try the functions like this for example: $data = gzinflate(substr($raw_data, 10, -8));
.
There is a relatively easy workaround for this problem though: use cURL instead of file_get_contents()
(use the CURLOPT_RETURNTRANSFER
option). cURL has native support for compressed responses as long as the content-encoding
header is present, and will transparently decompress the response body without you having to do anything.