How can a CSV file be created and written to in PHP, based on data retrieved from a URL?

To create and write data to a CSV file in PHP based on data retrieved from a URL, you can use functions like file_get_contents() to fetch the data from the URL, then parse and format it as needed before writing it to a CSV file using fputcsv().

<?php
// Retrieve data from URL
$url = 'https://example.com/data.csv';
$data = file_get_contents($url);

// Parse data as needed
$rows = explode("\n", $data);
$csvData = [];

foreach ($rows as $row) {
    $csvData[] = str_getcsv($row);
}

// Write data to CSV file
$csvFile = fopen('output.csv', 'w');
foreach ($csvData as $row) {
    fputcsv($csvFile, $row);
}
fclose($csvFile);

echo 'CSV file created and data written successfully!';
?>