I need to make a curl request, I have this line "curl -X POST -H 'Content-Type: application/json' -d" and need to "translate" to PHP curl. The problem is I don't know what the "-X", "-H" and "-d" mean.
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'Content-Type: application/json',
'Content-Length: '. strlen($itemJson))
);
I tried something like that on header ($itemJson
is a JSON string) but I got error 400.
I think I'm doing the request in a wrong way. Can anybody help me?
Send JSON data via POST with PHP cURLInitiate new cURL resource using curl_init(). Setup data in PHP array and encode into a JSON string using json_encode(). Attach JSON data to the POST fields using the CURLOPT_POSTFIELDS option. Set the Content-Type of request to application/json using the CURLOPT_HTTPHEADER option.
To post JSON data using Curl, you need to set the Content-Type of your request to application/json and pass the JSON data with the -d command line parameter. The JSON content type is set using the -H "Content-Type: application/json" command line parameter. JSON data is passed as a string.
Uses of cURL in PHPcURL is a PHP extension that allows you to use the URL syntax to receive and submit data. cURL makes it simple to connect between various websites and domains. Obtaining a copy of a website's material. Submission of forms automatically, authentication and cookie use.
If you have data in the form of a dictionary or any Python object, you can convert it into JSON like this. Use The json parameter: The requests module provides a json parameter that we can use to specify JSON data in the POST method. i.e., To send JSON data, we can also use the json parameter of the requests.
You can try as below
$data = array("name" => "Hagrid", "age" => "36");
$data_string = json_encode($data);
$ch = curl_init('http://somedomain.com/test.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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With