In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP.
cURL :
It stands for Client URL.
It is a command line tool for sending and getting files using URL syntax.
cURL allows communicating with other servers using HTTP, FTP, Telnet, and more.
Approach:
We are going to fetch JSON data from one of free website, which gives JSON data for testing i.e. reqres.in
First, we initialize curl using curl_init() method.
Sending GET request to reqres.in server using curl_setopt() method with CURLOPT_URL to get json data.
After that, we have to tell curl to store json data in a variable instead of dumping on screen. This is done by using CURLOPT_RETURNTRANSFER parameter in curl_setopt() function.
Execute curl using curl_exec() method.
At last, close the curl using curl_close() method.
Example:
PHP
<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,
curl_setopt($curl,
CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
if($e = curl_error($curl)) {
echo $e;
} else {
$decodedData =
json_decode($response, true);
var_dump($decodedData);
}
curl_close($curl);
?>
Output:
GET Request using cURL
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
01 Apr, 2022
Like Article
Save Article