Home >Backend Development >PHP Tutorial >How Can I Efficiently Export MySQL Query Results to a CSV File Using PHP?
Exporting MySQL Query Results to CSV in PHP
Question:
What's the best method for efficiently converting a MySQL query to a CSV file in PHP?
Answer:
There are multiple approaches to exporting MySQL query results to CSV using PHP:
1. Using MySQL's SELECT INTO OUTFILE:
This method allows you to directly output the query results to a CSV file, without using temp files:
SELECT * INTO OUTFILE "c:/mydata.csv" FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY "\n" FROM my_table;
Refer to the MySQL documentation for more details.
2. Manual Export and Formatting:
You can perform the export and formatting manually using PHP:
$select = "SELECT * FROM table_name"; $export = mysql_query($select) or die("Sql error : " . mysql_error()); $fields = mysql_num_fields($export); // Generate header for ($i = 0; $i < $fields; $i++) { $header .= mysql_field_name($export, $i) . "\t"; } // Generate data while ($row = mysql_fetch_row($export)) { $line = ''; foreach ($row as $value) { // Handle empty values if (empty($value)) { $value = "\t"; } else { // Escape double quotes $value = str_replace('"', '""', $value); $value = '"' . $value . '"' . "\t"; } $line .= $value; } $data .= trim($line) . "\n"; } // Remove leading/trailing whitespace $data = str_replace("\r", "", $data); // Send headers and output CSV header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=your_desired_name.xls"); header("Pragma: no-cache"); header("Expires: 0"); print "$header\n$data";
The above is the detailed content of How Can I Efficiently Export MySQL Query Results to a CSV File Using PHP?. For more information, please follow other related articles on the PHP Chinese website!