How to send data as JSON in a cURL POST request in PHP?

To send data as JSON in a cURL POST request in PHP, you can follow the steps below:

  1. Create an array or object containing the data you want to send as JSON.
  2. Convert the array or object to JSON format using json_encode() function.
  3. Set the Content-Type header to application/json to indicate that you are sending JSON data.
  4. Set the CURLOPT_POSTFIELDS option of cURL to the JSON data.
  5. Execute the cURL request.

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.