What are the advantages of using CURL over stream_get_contents for fetching external content in PHP?

When fetching external content in PHP, using CURL over stream_get_contents offers several advantages. CURL provides more options and flexibility for making HTTP requests, such as setting custom headers, handling redirects, and supporting different protocols. Additionally, CURL has better error handling capabilities and performance compared to stream_get_contents.

// Using CURL to fetch external content
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com/api/data');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

if($response === false){
    echo 'CURL Error: ' . curl_error($ch);
}

curl_close($ch);

// Process the response data
echo $response;