July 14, 2009

Export MySQL Data to CSV Using PHP

15 minutes into writing this article, I realized that PHP 5.1 now includes the fputcsv function that was missing from earlier versions of PHP. It formats a line (passed as a fields array) as CSV and write it (terminated by a newline) to the specified file handle. However, it is not properly documented what exactly is the "newline" character; is it CR, LF or CRLF.

I have a habit of re-inventing the wheel, so I've put together a substitute for this function that echoes the CSV data instead of writing to a file and (tries to) closely follow the recommendations described in RFC 4180.

<?php
/*
 * PHP code to export MySQL data to CSV
 * https://salman-w.blogspot.com/2009/07/export-mysql-data-to-csv-using-php.html
 *
 * Sends the result of a MySQL query as a CSV file for download
 */

/*
 * establish database connection
 */

$conn = mysql_connect('MYSQL_HOST', 'MYSQL_USERNAME', 'MYSQL_PASSWORD') or die(mysql_error());
mysql_select_db('MYSQL_DATABASE', $conn) or die(mysql_error($conn));

/*
 * execute sql query
 */

$query = sprintf('SELECT * FROM MYSQL_TABLE');
$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');
header('Content-Disposition: attachment;filename=export.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";
}
?>

This example code sends the CSV data to the browser along with appropriate headers that should pop-up the "Open/Save As..." dialog.