How can PHP's fputcsv function be used for CSV export and download?
To export data as a CSV file in PHP, you can use the fputcsv function to write data to a file in CSV format. To offer this CSV file for download, you can use the appropriate headers to indicate that the response is a downloadable file.
<?php
// Data to be exported
$data = [
['John Doe', 'john.doe@example.com', 'New York'],
['Jane Smith', 'jane.smith@example.com', 'Los Angeles'],
['Alice Johnson', 'alice.johnson@example.com', 'Chicago']
];
// File name for download
$filename = 'export.csv';
// Open file handle for writing
$handle = fopen($filename, 'w');
// Write data to CSV file
foreach ($data as $row) {
fputcsv($handle, $row);
}
// Close file handle
fclose($handle);
// Set headers for CSV download
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=' . $filename);
// Output file contents
readfile($filename);
// Delete file after download
unlink($filename);