php (35) javascript (31) phpjavascript (30) jquery (23) html (20) mysql (14) database (9) codeigniter (4) json (4) bar chart (2) calendar (2) column chart (2) framework (2) google maps (2) query (2) tables (2) url (2) dropdown (1)

Monday, January 29, 2018

How to Send and Receive JSON Data with PHP using cURL?

cURL is a tool to transfer data from server to client or vice versa. There are many protocols used by cURL such that FILE, FTP, HTTPS, POP3, SMTP, TELNET etc. 

Following steps requires  to send JSON data via post request with PHP cURL:
Step-1: First we will specify URL ($url) where the JSON data need to be send.
Step-2: Initiate cURL resource using curl_init().
step-3: Encode PHP array data into a JSON string using json_encode().
step-4: Attach JSON data to the POST field using the CURLOPT_POSTFIELDS option.
step-5:  Set header option to Content-Type: application/json
step-6: Return response as string CURL_RETURNTRANSFER option
Step-7: Finally curl_exec() function is used to execute the POST request api url.

In the following example code, We will pass POST data on API URL as JSON format.
$name="Durga Prasad Padhan";
$data =array("Voter ID" =>$id,"Name" =>$name,"Address" =>$address,"Phone"=>$phone);
$newData = curl_init( $url );
# Setup request to send json via POST.
$person = json_encode( array( "Person"=> $data ) );
curl_setopt( $newData, CURLOPT_POSTFIELDS, $person );
curl_setopt($newData, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt( $newData, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
# Return response instead of printing.
curl_setopt( $newData, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($newData);
# Print response.
echo "<pre>" . $result. "</pre>";
In the following code, We will Receive JSON POST data using PHP.
1st: jsone_decode() function is used to decode JSON data into array format .
2nd: file_get_content() function is used to receivedata in readable format.
$data = json_decode(file_get_contents('php://input'), true);


  1. I recently came across your blog and have now been reading along. I believed I could leave my first comment. I don't know what to state except that I've enjoyed reading. Nice blog. I will keep visiting this blog very often.
    affiliate marketing singapore

  2. Thank you very much for your valuable information. Digital Signature Certificate

  3. Thanks for sharing such an awesome post. This is very informative and helpful, share more post like. Digital Signature Certificate

  4. This is very informative and helpful, share more post like. Class 2 Digital Signature Certificate

  5. I highly admire your post. Thanks for sharing such wonderful information, I see your post very often and share them on all social media channels.
    Digital Signature Certificate in Delhi


More Posts