How can the Content-Type header be properly set and sent in a cURL request in PHP to ensure successful data transfer?
To properly set and send the Content-Type header in a cURL request in PHP, you can use the `CURLOPT_HTTPHEADER` option to specify the header value. This ensures that the server knows the type of data being sent and can process it correctly.
// Initialize cURL session
$ch = curl_init();
// Set the URL to send the request to
curl_setopt($ch, CURLOPT_URL, 'https://example.com/api');
// Set the request method to POST
curl_setopt($ch, CURLOPT_POST, 1);
// Set the request body data
$data = array('key1' => 'value1', 'key2' => 'value2');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
// Set the Content-Type header to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
// Execute the cURL request
$response = curl_exec($ch);
// Close cURL session
curl_close($ch);
// Handle the response data
echo $response;