How can the use of urlencode() function affect the success of a cURL request in PHP?

When making a cURL request in PHP, if the data being sent in the request is not properly encoded using urlencode(), it can result in errors or unexpected behavior. To ensure the success of the cURL request, it is important to properly encode the data before sending it.

// Data to be sent in the cURL request
$data = [
    'key1' => 'value 1',
    'key2' => 'value 2',
];

// Encode the data using urlencode()
$encoded_data = http_build_query($data);

// Initialize cURL session
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, 'https://example.com/api');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded_data);

// Execute cURL session
$response = curl_exec($ch);

// Close cURL session
curl_close($ch);

// Handle response
echo $response;