/* * PHP code to export MySQL data to CSV * * Sends the result of a MySQL query as a CSV file for download * Easy-to-convert to UTF-8. */ /* * Establish database connection */ $conn = mysql_connect (' localhost ', ' login ', ' pass ') or Die (Mysql_error ()); mysql_select_db (' database_name ', $conn) or Die (Mysql_error ($conn)); mysql_query ("SET NAMES CP1252"); /* * Execute SQL query */ $query = sprintf (' SELECT field1,field2 from table_name '); $result = mysql_query ($query, $conn) or Die (Mysql_error ($conn)); /* * Send response headers to the browser * Following headers instruct the browser to treat the data as a CSV file called Export.csv */ Header (' content-type:text/csv; charset=cp1252 '); Header (' content-disposition:attachment;filename=output.csv '); /* * Output header row (if atleast one row exists) */ $row = Mysql_fetch_assoc ($result); if ($row) { Echocsv (Array_keys ($row)); } /* * Output data rows (if atleast one row exists) */ while ($row) { Echocsv ($row); $row = Mysql_fetch_assoc ($result); } /* * echo the input array as CSV data maintaining consistency with most CSV implementations *-Uses double-quotes as enclosure when necessary *-Uses double double-quotes to escape double-quotes *-Uses CRLF as a line separator */ function Echocsv ($fields) { $separator = "; foreach ($fields as $field) { if (Preg_match ('/\\r|\\n|,| ' /', $field)) { $field = ' "'. Str_replace (' "', '" ' "', $field) '; } Echo $separator. $field; $separator = ', '; } echo "\ r \ n"; } ?> |