How to export mysql table data into csv file using php


This PHP script will export all the mysql table data into a csv file.

<?
$dbconnection;
$table="members";

$csv = NULL;
/* link identifier from db connection */

$r = mysql_query("show columns from ".$table);
while ($row = mysql_fetch_assoc($r)) {
$csv .= $row['col_name'].',';
}
$csv = substr($csv, 0, -1)."n";
$r = mysql_query("select * from ".$table);
while ($row = mysql_fetch_assoc($r)) {
$csv .= '"'.join('","', str_replace('"', '""', $row)).""n";
}
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv; filename=" . date("Y-m-d") ."_".$table.".csv; size=".strlen($csv));
echo $csv;
exit;
?>

Related Posts:

One Responses


Kevin Korb February 12, 2009 at 10:34 am

Very nice.

I also wrote something similar, but works for Muti-dimentional arrays instead of database results.

Create CSV Files From Multi-dimentional arrays in PHP


Comments are closed.