When we work on web services it is generally required to send json data via POST method.
In this tutorial we will see how to post json data with PHP curl.
It is very easy to post data in json form using header Content-Type: application/json in CURLOPT_HTTPHEADER.
Here we put data in PHP array and encode into a JSON string using json_encode() function.
Let’s see how to send json data via post method
<?php $url = 'https://www.website.com/ws/filename.php'; $data = array("first_name" => "First name","last_name" => "last name","email"=>"myemail@gmail.com"); $data_string = json_encode($data); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); $err = curl_error($ch); if ($err) { echo "cURL Error #:" . $err; } else { echo $result; //display response } curl_close($ch); ?>
Also Read: How to Receive JSON POST with PHP