php curl post raw json code example
Example 1: curl pass raw json in post request
If you wanna use Content-type: application/json and raw data, seem your data
should be in json format
$ch = curl_init();
$headers = [
'x-api-key: XXXXXX',
'Content-Type: text/plain'
];
$postData = [
'data1' => 'value1',
'data2' => 'value2'
];
curl_setopt($ch, CURLOPT_URL,"XXXXXX");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec ($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
Example 2: how to do a post with json body curl php
// API URL$url = 'http://www.example.com/api';// Create a new cURL resource$ch = curl_init($url);// Setup request to send json via POST$data = array( 'username' => 'codexworld', 'password' => '123456');$payload = json_encode(array("user" => $data));// Attach encoded JSON string to the POST fieldscurl_setopt($ch, CURLOPT_POSTFIELDS, $payload);// Set the content type to application/jsoncurl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));// Return response instead of outputtingcurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);// Execute the POST request$result = curl_exec($ch);// Close cURL resourcecurl_close($ch);