Aliso the Geek

A coder in love with WordPress.

PHP code for exporting a MySQL table to a CSV file

After a lot of searching, and a lot of troubleshooting, I finally found PHP code for exporting a CSV file from MySQL that works perfectly! This might be old news to some, but I’d never done it before and I needed to have that export feature on my Store Locator plugin.

$result = mysql_query("SHOW COLUMNS FROM $table");
while ($row = mysql_fetch_assoc($result)) {
    $csv_output .= $row['Field'].',';
}
$csv_output = substr($csv_output, 0, -1)."n";

$values = mysql_query("SELECT * FROM $table");
while ($row = mysql_fetch_assoc($values)) {
    $csv_output .= '"'.join('","', str_replace('"', '""', $row)).""n";
}

header("Content-type: application");
header("Content-disposition: csv; filename=" . date("Y-m-d") . "_".$table.".csv; size=".strlen($csv_output));

print $csv_output;

exit;