Return to Snippet

Revision: 10822
at January 15, 2009 00:09 by mikegreen

Initial Code
$result = mysql_query("SELECT * FROM table ORDER BY column DESC");

// I hard-code the column names so I can capitalize, add spaces, etc.
$fields = '"User ID","Name","Email","Registration Date"'."\n";

// Iterate through the rows of data
while ($row = mysql_fetch_assoc($result))
	$fields .= '"'.$row['id'].'","'.$row['name'].'","'.$row['email'].'","'.$row['registration_date'].'"'."\n";

// Set our headers
header('Content-type: text/csv');
// To display data in-browser, change the header below to:
// header("Content-Disposition: inline");
header("Content-Disposition: attachment; filename=event_registrations.csv");

// Output our data
echo $fields;

Initial URL

Initial Description
# Export MySQL Data as CSV

This code takes a `mysql_query()` resource and outputs its rows into CSV spreadsheet format. Edit the `header('Content-Disposition...` declaration to tell the user's browser to either display the data as plain text or download it as an `attachment`.

__Note:__ This doesn't include the code to connect to the database in the first place. Don't forget that, otherwise this code is pretty useless.

Initial Title
Export MySQL Data as CSV

Initial Tags
mysql, php, csv, excel

Initial Language