Sending JSON DATA with PHP cURL

Sometimes APIs wants you to send json data. in such cases cURL we need to make some additions to post operations with cURL.

The relevant code can be found below.

Also the technique of taking in the posted place is a little bit different, you can find it in part 2.


$data = array("name" => "phpExample", "age" => "27");                                                                    
$data_string = json_encode($data);                                                                                   
$ch = curl_init('http://localhost/xxx.php');                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                       
$result = curl_exec($ch);

echo $result;

In xxx.php that we made the request we are taking the json data a little different than taking with $_POST. That way is this;

$posts = file_get_contents('php://input');
$jsonData = json_decode($posts, true);



There are no comments, make the firs comment