How can cURL be utilized to fetch data from an online server to a local server in PHP?

To fetch data from an online server to a local server in PHP, cURL can be utilized. cURL is a library that allows you to make HTTP requests and retrieve data from remote servers. By using cURL in PHP, you can easily fetch data from an online server and save it on your local server for further processing.

<?php

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

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

// Set the file where the fetched data will be saved
$fp = fopen('local_data.json', 'w');
curl_setopt($ch, CURLOPT_FILE, $fp);

// Execute the cURL session
curl_exec($ch);

// Close cURL session and file pointer
curl_close($ch);
fclose($fp);

echo 'Data fetched and saved successfully.';
?>