How to use cURL to Get JSON Data and Decode JSON Data in PHP ?


cURL is a command-line tool for transferring data using various protocols. It is also a popular library in PHP for making HTTP requests. Here's how to use cURL to get JSON data and decode it in PHP:

  • Using cURL to get JSON data:

To use cURL to get JSON data, you need to set the CURLOPT_RETURNTRANSFER option to true to return the response as a string. You also need to set the CURLOPT_URL option to the URL of the JSON data you want to retrieve. Here's an example:

$url = 'https://example.com/data.json';

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);

$response = curl_exec($ch);

curl_close($ch);

In this example, we're retrieving JSON data from https://example.com/data.json and storing the response in the $response variable.

  • Decoding JSON data in PHP:

Once you have the JSON data, you can use the json_decode() function in PHP to decode it into an array or object. Here's an example:

$data = json_decode($response, true);

// Accessing the decoded data
echo $data['name'];
echo $data['age'];

In this example, we're using the json_decode() function to decode the JSON data stored in the $response variable into an associative array. The second parameter of json_decode() is set to true to return an array instead of an object.

We can then access the decoded data using the keys of the associative array.

  • Putting it all together:

Here's an example that combines both steps to retrieve and decode JSON data using cURL and PHP:

$url = 'https://example.com/data.json';

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);

$response = curl_exec($ch);

curl_close($ch);

$data = json_decode($response, true);

// Accessing the decoded data
echo $data['name'];
echo $data['age'];

In this example, we're retrieving JSON data from https://example.com/data.json, storing the response in the $response variable, decoding the JSON data into an associative array using json_decode(), and then accessing the decoded data using the keys of the associative array.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.