How to Create and Download a CSV File from a PHP Script
Creating and downloading a CSV file from a PHP array is a useful technique in website development. Here's a detailed guide for novice programmers:
Creating the CSV File
Example:
$array = [ ['fs_id' => '4c524d8abfc6ef3b201f489c', 'name' => 'restaurant', ...], // More array elements... ]; $delimiter = ','; $csv = fopen('tmp.csv', 'w'); foreach ($array as $line) { fputcsv($csv, $line, $delimiter); }
Downloading the CSV File
header('Content-Disposition: attachment; filename="filename.csv"'); header('Content-Type: text/csv');
fseek($csv, 0); // Reset the file pointer to the start fpassthru($csv);
Putting It All Together
The following function combines both steps and allows you to download a CSV file from an array:
function array_to_csv_download($array, $filename = 'export.csv', $delimiter = ',') { // Set HTTP headers header('Content-Disposition: attachment; filename="' . $filename . '"'); header('Content-Type: text/csv'); // Create a file pointer $csv = fopen('php://memory', 'w'); // Loop through the array and create CSV lines foreach ($array as $line) { fputcsv($csv, $line, $delimiter); } // Send the generated CSV to the browser fpassthru($csv); }
Usage:
$array = [ ['fs_id' => '4c524d8abfc6ef3b201f489c', 'name' => 'restaurant', ...], // More array elements... ]; array_to_csv_download($array, 'restaurants.csv'); // The CSV file will be downloaded to the user's computer.
Additional Note:
As an alternative to using php://memory, you can also use php://output for the file descriptor, which may be more efficient for large datasets.
This method provides a straightforward way to create and download CSV files from PHP arrays, making it a valuable tool for website developers.
The above is the detailed content of How to Download a CSV file from a PHP Array?. For more information, please follow other related articles on the PHP Chinese website!