/* * 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-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 "; } ?> |