Asked  7 Months ago    Answers:  2   Viewed   29 times

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

{
    "expires_in":5180976,
    "access_token":"AQXzQgKTpTSjs-qiBh30aMgm3_Kb53oIf-VA733BpAogVE5jpz3jujU65WJ1XXSvVm1xr2LslGLLCWTNV5Kd_8J1YUx26axkt1E-vsOdvUAgMFH1VJwtclAXdaxRxk5UtmCWeISB6rx6NtvDt7yohnaarpBJjHWMsWYtpNn6nD87n0syud0"
} 

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

So how can I retrieve it through PHP?

 Answers

96
$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 https://paragonie.com/blog/2017/10/certainty-automated-cacert-pem-management-for-php-software
// 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);
curl_close($ch);

$obj = json_decode($result);
echo $obj->access_token;
Wednesday, March 31, 2021
 
uiroshan
answered 7 Months ago
43

The link provided starts with

{ data :

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

$json = file_get_contents('http://nhs-sh.cfpreview.co.uk/api/version/fetchLatestData?dataType=Clinics&versionNumber=-1&uuID=website&dt=');
$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, May 29, 2021
 
Whakkee
answered 5 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :