Home > Backend Development > PHP Tutorial > How to Extract a JSON Object and Its Access Token from a URL Using PHP?

How to Extract a JSON Object and Its Access Token from a URL Using PHP?

Mary-Kate Olsen
Release: 2024-11-23 03:43:09
Original
481 people have browsed it

How to Extract a JSON Object and Its Access Token from a URL Using PHP?

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"
}
Copy after login

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;
Copy after login

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;
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template