Home >Backend Development >PHP Tutorial >How to Generate and Download a CSV File from a MySQL Database using PHP?
How to Create and Download a CSV File for a User in PHP
Question:
A user has requested to retrieve data from a MySQL database as a CSV file. How can a PHP script generate the CSV file and prompt the user to download it when they visit a URL?
Answer:
To create and download a CSV file in PHP:
header("Content-Type: text/csv"); header("Content-Disposition: attachment; filename=file.csv"); function outputCSV($data) { $output = fopen("php://output", "wb"); foreach ($data as $row) fputcsv($output, $row); // here you can change delimiter/enclosure fclose($output); } outputCSV(array( array("name 1", "age 1", "city 1"), array("name 2", "age 2", "city 2"), array("name 3", "age 3", "city 3") ));
Explanation:
Output CSV Header:
Output CSV Function (outputCSV):
Output CSV Data:
The above is the detailed content of How to Generate and Download a CSV File from a MySQL Database using PHP?. For more information, please follow other related articles on the PHP Chinese website!