How to export mysql table data into csv file using php

February 12th, 2009One Comment

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:

Tagged : , ,

One Responses

  1. 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