Generating CSV Files for Users in PHP
Users often request data extracts in CSV format. This article delves into the process of creating CSV files on demand and delivering them to users through a downloadable link.
Solution:
To create and download a CSV file containing data from a MySQL database when a user clicks a link:
Generate the CSV Data:
Create the CSV Header:
Define a CSV Output Function:
Call the CSV Output Function:
Example Code:
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") ));
Key Points:
The above is the detailed content of How Can I Generate and Download CSV Files from a MySQL Database Using PHP?. For more information, please follow other related articles on the PHP Chinese website!