This article aims to provide a comprehensive solution for creating and downloading a CSV (Comma-Separated Values) file from a PHP array. As a novice programmer, you may need assistance implementing this functionality.
To generate CSV lines from your PHP array, you can utilize the built-in fputcsv() function, which converts arrays into formatted strings suitable for CSV:
$f = fopen("tmp.csv", "w"); foreach ($array as $line) { fputcsv($f, $line); }
To initiate a file download from the browser, sending appropriate HTTP headers is crucial. One such header is:
header('Content-Disposition: attachment; filename="filename.csv";');
This header informs the browser that the response contains a file attachment with the specified filename.
Combining the CSV line generation and HTTP header, you can create a function for downloading CSVs:
function array_to_csv_download($array, $filename = "export.csv", $delimiter = ";") { // Open a memory file for efficient handling without temporary files. $f = fopen('php://memory', 'w'); // Generate CSV lines and write them to the memory file. foreach ($array as $line) { fputcsv($f, $line, $delimiter); } // Reset the file pointer to begin sending the file. fseek($f, 0); // Set CSV-related HTTP headers. header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename="'. $filename . '";'); // Output the generated CSV lines to the browser for download. fpassthru($f); }
To use this function, simply pass your array and desired filename:
array_to_csv_download(array( array(1, 2, 3, 4), // First row array(1, 2, 3, 4) // Second row ), "numbers.csv");
As an alternative to writing to a memory file, you can also use php://output as the file descriptor, eliminating the need for file seeking:
function array_to_csv_download($array, $filename = "export.csv", $delimiter = ";") { header('Content-Type: application/csv'); header('Content-Disposition: attachment; filename="'. $filename . '";'); // Open the php://output stream for direct output. $f = fopen('php://output', 'w'); foreach ($array as $line) { fputcsv($f, $line, $delimiter); } }
The above is the detailed content of How to Programmatically Download CSV Files from a PHP Array?. For more information, please follow other related articles on the PHP Chinese website!