Plastic Plastic - 4 months ago 51
PHP Question

Get JSON from url with file_get_contents

I have a server that provide some data in JSON.
I tried to get these data with the usual:

$res = file_get_contents($url);
$result = json_decode($res);

But $result is yet a string.
The problem is that the data that comes from file_get_content has some alphanumerical string before data and a zero after.

something like:

{"@attributes":{"ticker":"FCA"},"info...... // here all json data

I already checked json validity directly from the url and it's properly formatted, I can not understand where zero and 215ba come from.

Obviously I could strip the strings eliminating both but I was wondering if there was a more concrete solution instead of a workaround

PS: unfortunately I can not use cURL


Note on the docs for json_decode:

This function only works with UTF-8 encoded strings..

Something like this might fix it:

$contents = file_get_contents($url);
$contents = utf8_encode($contents);
$results = json_decode($contents); 

If that's not working you could use regex to check for new lines. Assuming the json will always be on 1 line.

$contents = file_get_contents($url);
$contents = utf8_encode($contents);
preg_match('/^.+[\n](.+)[\n]./', $contents, $matches);

//the json is in $matches[1]