Post JSON data via PHP cURL
Post JSON data via PHP cURL
We can Post JSON data via PHP curl by using header Content-Type: application/json in CURLOPT_HTTPHEADER. Below is working code demonstration of PHP curl with post json field.
<?php
$url = 'http://yourdomain.com';
$jsonString = json_encode(array("key" => "value"));
// You can directly replace your JSON string with $jsonString variable.
$ch = curl_init();
$timeout = 0; // Set 0 for no timeout.
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($jsonString),)
);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$result = curl_exec($ch);
curl_close($ch);
?>- curl_setopt : Set an option for a cURL transfer
- CURLOPT_URL : URL to send curl request
- CURLOPT_CUSTOMREQUEST : Custom http request method like GET,POST,CONNECT
- CURLOPT_POSTFIELDS : Post fields.
- CURLOPT_RETURNTRANSFER : Set true if Return the response as a string instead of outputting it to the screen
- CURLOPT_CONNECTTIMEOUT : Number of seconds to allow cURL functions to execute. set 0 if for not timeout
- CURLOPT_HTTPHEADER : An array of HTTP header fields to set, in the format array(‘Content-type: text/plain’, ‘Content-length: 100’) or array(‘Content-type: application/json’, ‘Content-length: 300’)
(Visited 800 times, 13 visits today)

Thanks Dear.
Thanks bro