Posting JSON data with PHP cURL

This is where you share YOUR scripts with others

Moderators: egami, macek, gesf

Post Reply
phpkiller
New php-forum User
New php-forum User
Posts: 35
Joined: Thu Jun 28, 2012 2:11 pm

Sun Jun 12, 2016 9:58 pm

You have to add JSON content type with your request header just like below example:

$post_data = array("OS" => "Android", "version" => "5.1");
$json_string = json_encode($post_data);

$ch = curl_init('http://myapi/opeartingsystems/ver'); // request URL
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_string))
);

$response = curl_exec($ch);

Post Reply