Home > Backend Development > PHP Tutorial > How to Fetch and Decode JSON Data with cURL in PHP?

How to Fetch and Decode JSON Data with cURL in PHP?

Barbara Streisand
Release: 2024-12-04 05:55:15
Original
760 people have browsed it

How to Fetch and Decode JSON Data with cURL in PHP?

Fetching and Decoding JSON Data Using cURL in PHP

To extract data from a JSON response using cURL in PHP, follow these steps:

1. Initiate cURL

$ch = curl_init();
Copy after login

2. Configure cURL Options

Set the CURLOPT_RETURNTRANSFER option to true to return the response instead of printing it. Specify the URL using CURLOPT_URL.

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
Copy after login

3. Execute cURL Request

Invoke curl_exec to execute the request and store the JSON response in the $result variable.

$result = curl_exec($ch);
Copy after login

4. Decode JSON Response

Use json_decode to convert the JSON response into a PHP array.

$array = json_decode($result, true);
Copy after login

5. Extract Data from Array

Access the data from the array using the appropriate keys. For example, to get the thread title with ID 13:

echo $array["threads"][13]["title"];
Copy after login

To get the message of the post with ID 23:

echo $array["threads"][13]["content"]["content"][23]["message"];
Copy after login

The above is the detailed content of How to Fetch and Decode JSON Data with cURL in 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