Home >Backend Development >PHP Tutorial >How to Retrieve JSON Data from a URL in PHP?

How to Retrieve JSON Data from a URL in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-17 15:45:02571browse

How to Retrieve JSON Data from a URL in PHP?

Retrieving JSON Data from URL in PHP

This article addresses a common issue faced by PHP programmers: retrieving JSON objects from URLs. We will explore methods to accomplish this task and provide comprehensive code examples.

Problem:

You have a URL that returns a JSON object, and you want to retrieve specific data from it, such as the "access_token" value.

Solution:

Method 1: file_get_contents()

$json = file_get_contents('url_here');
$obj = json_decode($json);
echo $obj->access_token;

Note that file_get_contents requires allow_url_fopen to be enabled. You can also use ini_set("allow_url_fopen", 1) to enable it at runtime.

Method 2: curl

$ch = curl_init();
// Warning: This line poses a security risk.
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;

By utilizing these methods, you can easily retrieve JSON objects from URLs and access their contents in PHP.

The above is the detailed content of How to Retrieve JSON Data from a URL in PHP?. 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