Home >Backend Development >PHP Tutorial >How to Generate On-Demand CSV Files from a MySQL Database using PHP?
Creating a CSV File on Demand with PHP
When working with user data stored in a MySQL database, it can be convenient to provide an option to export that data as a CSV file. This allows users to easily download and manipulate their data offline. To create a CSV file dynamically in PHP and enable users to download it, follow these steps:
Step 1: Prepare PHP Headers
Use the header() function to set appropriate headers for the response:
header("Content-Type: text/csv"); header("Content-Disposition: attachment; filename=file.csv");
This sets the content type as CSV and prompts the user to download the file with the specified filename.
Step 2: Define Output CSV Function
Create a function to output the CSV data in the appropriate format:
function outputCSV($data) { $output = fopen("php://output", "wb"); foreach ($data as $row) fputcsv($output, $row); // here you can change delimiter/enclosure fclose($output); }
This function uses the fopen() function to open a file handle for output, iterates over the provided $data and writes each row as a CSV line using fputcsv(), and finally closes the file.
Step 3: Execute the Output CSV Function
Replace the placeholder data with the actual data you want to export from your MySQL database and call the outputCSV() function:
outputCSV(array( array("name 1", "age 1", "city 1"), array("name 2", "age 2", "city 2"), array("name 3", "age 3", "city 3") ));
This example generates a CSV file with three rows containing name, age, and city information.
By following these steps, you can create a CSV file on the fly based on data from your MySQL database and enable users to download it when they click a link. The php://output function allows you to write directly to the HTTP output stream, while the fputcsv() function formats the data into a CSV-compatible format.
The above is the detailed content of How to Generate On-Demand CSV Files from a MySQL Database using PHP?. For more information, please follow other related articles on the PHP Chinese website!