Home >Backend Development >PHP Tutorial >How to Access JSON Objects from URLs in PHP and Extract the Access Token?

How to Access JSON Objects from URLs in PHP and Extract the Access Token?

Barbara Streisand
Barbara StreisandOriginal
2024-11-15 04:06:02663browse

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!

Statement:
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