What are best practices for structuring and organizing cURL requests in PHP scripts to avoid errors and improve readability?

When making cURL requests in PHP scripts, it is important to structure and organize the code properly to avoid errors and improve readability. One best practice is to separate the cURL configuration settings from the actual request execution. This can be achieved by defining an array of options for the cURL request and using the curl_setopt_array() function to set these options. Additionally, using functions or classes to encapsulate the cURL logic can help make the code more modular and easier to maintain.

// Define cURL configuration settings
$curlOptions = array(
    CURLOPT_URL => 'https://api.example.com',
    CURLOPT_RETURNTRANSFER => true,
    // Add more options as needed
);

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

// Set cURL options
curl_setopt_array($ch, $curlOptions);

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

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

// Close cURL session
curl_close($ch);

// Process the response data
echo $response;