To send data as JSON in a cURL POST request in PHP, you can follow the steps below:
json_encode()
function.Content-Type
header to application/json
to indicate that you are sending JSON data.CURLOPT_POSTFIELDS
option of cURL to the JSON data.Here's an example code snippet:
// Data to send as JSON
$data = [
'name' => 'John',
'email' => '[email protected]'
];
// Convert data to JSON format
$jsonData = json_encode($data);
// cURL initialization
$curl = curl_init();
// Set cURL options
curl_setopt($curl, CURLOPT_URL, 'https://example.com/api/endpoint');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
]);
// Execute cURL request
$response = curl_exec($curl);
// Close cURL session
curl_close($curl);
// Handle response
if ($response === false) {
// Failed cURL request
echo 'Error: ' . curl_error($curl);
} else {
// Successful cURL request
echo 'Response: ' . $response;
}
Make sure to replace 'https://example.com/api/endpoint'
with the actual endpoint URL you want to send the request to.