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;

No related posts.

This entry was posted in General, MySQL, PHP, Personal. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>