Asked  2 Years ago    Answers:  2   Viewed   62 times

I have a URL that returns a JSON object like this:


I want to get JSON object from the URL and then the access_token value.

So how can I retrieve it through PHP?


$json = file_get_contents('url_here');
$obj = json_decode($json);
echo $obj->access_token;

For this to work, file_get_contents requires that allow_url_fopen is enabled. This can be done at runtime by including:

ini_set("allow_url_fopen", 1);

You can also use curl to get the url. To use curl, you can use the example found here:

$ch = curl_init();
// IMPORTANT: the below line is a security risk, read
// in most cases, you should set it to true
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'url_here');
$result = curl_exec($ch);

$obj = json_decode($result);
echo $obj->access_token;
Saturday, September 17, 2022

The link provided starts with

{ data :

which is valid javascript but invalid json. You can test it on To fix this we can replace the data with "data" :

$json = file_get_contents('');
$obj = json_decode($json);

if (json_last_error() !== JSON_ERROR_NONE) { //check if there was an error decoding json
    $json = '{ "data" :'. substr(trim($json), 8); // replace the first 8-1 characters with { "data" :
    $obj = json_decode($json); 

print_r($obj->data); //show contents of data

Please note that this fix is dependent on the data source e.g. if they change data to dataset. The correct measure would be to ask the developers to fix their json implementation.

Saturday, November 5, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :

Browse Other Code Languages