Creating a CSV Export Feature Using PHP
In this blog post, we will learn how to create a CSV (Comma Separated Values) export feature using PHP. This feature is particularly useful when you want to export data from your application for further analysis or manipulation in spreadsheet applications like Microsoft Excel or Google Sheets.
Step 1: Retrieve the data that you want to export
For this example, we will use a simple PHP array to represent the data that we want to export. In a real-world application, this data would likely come from a database or some other data source.
# PHP
$data = [
['Name', 'Age', 'City'],
['John Doe', '25', 'New York'],
['Jane Smith', '28', 'Los Angeles'],
['Michael Brown', '31', 'Chicago'],
];
Step 2: Create a new CSV file and write the data to it
We will use PHP’s built-in functions fopen()
, fputcsv()
, and fclose()
to create a new CSV file, write the data to it, and close the file.
# PHP
$csvFilename = 'export.csv';
$csvFile = fopen($csvFilename, 'w');
foreach ($data as $row) {
fputcsv($csvFile, $row);
}
fclose($csvFile);
Step 3: Set the appropriate headers for the file download
To prompt the user to download the generated CSV file, we will set the appropriate HTTP headers using the header()
function.
# PHP
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $csvFilename . '"');
header('Content-Length: ' . filesize($csvFilename));
Step 4: Output the content of the CSV file
Finally, we will use the readfile()
function to output the content of the CSV file, which will prompt the user to download it.
# PHP
readfile($csvFilename);
Putting it all together: Now, let’s combine all the steps into a single PHP script:
# PHP
<?php
$data = [
['Name', 'Age', 'City'],
['John Doe', '25', 'New York'],
['Jane Smith', '28', 'Los Angeles'],
['Michael Brown', '31', 'Chicago'],
];
$csvFilename = 'export.csv';
$csvFile = fopen($csvFilename, 'w');
foreach ($data as $row) {
fputcsv($csvFile, $row);
}
fclose($csvFile);
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $csvFilename . '"');
header('Content-Length: ' . filesize($csvFilename));
readfile($csvFilename);
?>
Save this script as “export.php” and run it in your browser. You should be prompted to download a CSV file named “export.csv” containing the data from the $data
array.
Conclusion:
In this blog post, we learned how to create a CSV export feature using PHP. This is a useful skill to have, as it allows you to easily export data from your application for further analysis or manipulation in spreadsheet applications like Microsoft Excel or Google Sheets.