How to POST and GET JSON Data using PHP cURL

February 15, 2018 · 2 min read

In this PHP tutorial, I’m going to talk about how to POST and GET JSON Data using PHP cURL, the cURL library is used for sending and receiving data on the web and used by the developer for the same. And if you are working on the rich application then often need to post and get data to another server, Working with cURL and JSON is the best approach.

Code for POST JSON Data using PHP cURL

For demo first I created userData array then I converted an array in JSON because JSON is the fastest data type to travel from one server to other server. then specify the URL where the JSON data need to be sent after that initiate new cURL resource using by curl_init() function in PHP, then attach JSON data to the POST fields using the CURLOPT_POSTFIELDS option. Don’t forget to set Content-Type as application/json using CURLOPT_HTTPHEADER option.Finally, curl_exec() function is used to execute your POST request

$url = 'https://api.example.com/';
$ch = curl_init($url);
$userData = array(
'name' => 'techlifediary',
'email' => '[email protected]',
'city'=>'kerala',
'mobile'=>'0000000000'
);
$dataString= json_encode(array("userData" => $userData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($dataString))
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);

GET JSON POST Data using PHP cURL

You can simply use file_get_contents() to fetch JSON data then use json_decode() function in PHP to decode JSON data into array format.

$data = json_decode(file_get_contents('php://input'), true);
print_r($data);

How to create login page in PHP with MySQL database
Get information about your memory and CPU usage in PHP
Share on Facebook
Facebook
Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin
Pin on Pinterest
Pinterest