How can the code be optimized for better performance and reliability when using cURL in PHP?

To optimize the code for better performance and reliability when using cURL in PHP, it is recommended to reuse the cURL handle for multiple requests instead of creating a new one for each request. This can help reduce overhead and improve efficiency. Additionally, setting appropriate cURL options, such as setting timeouts and handling errors properly, can enhance the reliability of the code.

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

// Set cURL options
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);

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

// Check for errors
if(curl_errno($ch)){
    echo 'cURL error: ' . curl_error($ch);
}

// Close cURL handle
curl_close($ch);

// Process the response
echo $response;