How to Retrieve a JSON Object and Its Access Token from a URL Using PHP
Problem:
Given a URL endpoint that returns a JSON object like the one below, you want to use PHP to extract the JSON object and retrieve the "access_token" value:
{ "expires_in":5180976, "access_token":"AQXzQgKTpTSjs-qiBh30aMgm3_Kb53oIf-VA733BpAogVE5jpz3jujU65WJ1XXSvVm1xr2LslGLLCWTNV5Kd_8J1YUx26axkt1E-vsOdvUAgMFH1VJwtclAXdaxRxk5UtmCWeISB6rx6NtvDt7yohnaarpBJjHWMsWYtpNn6nD87n0syud0" }
Solution:
Using file_get_contents()
The file_get_contents() function allows you to obtain the contents of a URL. To retrieve the JSON object and extract the "access_token" value:
$json = file_get_contents('url_here'); $obj = json_decode($json); echo $obj->access_token;
Note that allow_url_fopen must be enabled in your PHP configuration for file_get_contents() to work.
Using cURL
cURL is an alternative method for retrieving the URL contents. Here's an example:
$ch = curl_init(); // For security reasons, this is a risk and should be set 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;
The above is the detailed content of How to Extract a JSON Object and Its Access Token from a URL Using PHP?. For more information, please follow other related articles on the PHP Chinese website!