Posting JSON data with PHP cURL

  • Thread starter Thread starter Anonymous
  • Start date Start date
A

Anonymous

Guest
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);
 
Back
Top