How can cURL be used as an alternative to file_get_contents in PHP?

When file_get_contents is disabled or not available on a server, cURL can be used as an alternative method to fetch remote data in PHP. cURL is a library that allows you to make HTTP requests and retrieve data from URLs. By using cURL functions in PHP, you can achieve similar functionality to file_get_contents.

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

// Set the URL to fetch
curl_setopt($ch, CURLOPT_URL, 'https://example.com/api/data');

// Set option to return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// Execute the cURL session and fetch the data
$data = curl_exec($ch);

// Close cURL session
curl_close($ch);

// Output the fetched data
echo $data;