Home > Article > Backend Development > How to Access JSON Objects from URLs in PHP and Extract the Access Token?
Accessing JSON Objects from URLs in PHP
To obtain a JSON object from a given URL and extract the "access_token" value in PHP, there are several approaches:
Using file_get_contents()
<?php $json = file_get_contents('url_here'); $obj = json_decode($json); echo $obj->access_token; ?>
Using curl
<?php $ch = curl_init(); // Enable SSL verification (set to true for production environments) curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); 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; ?>
To enable "file_get_contents", ensure that "allow_url_fopen" is set to "1" in your PHP configuration or use the following code:
<?php ini_set('allow_url_fopen', 1);
The above is the detailed content of How to Access JSON Objects from URLs in PHP and Extract the Access Token?. For more information, please follow other related articles on the PHP Chinese website!