Php function to convert an array to CSV file for download

Many times your PHP application may require downloading records from a database table. PHP MySQL select queries return result in associate array format (using mysqli_fetch_assoc or mysqli_result::fetch_assoc). Below function can be used to convert the result array into a CSV file. And then force download the generated CSV file.

/**
 ** convert input array to a csv file and force downlaod the same
 **
 ** should be called before any output is send to the browser
 ** input array should be an associative array
 ** the key of the associative array will be first row of the csv file
 ** 
 ** @param array $array
 ** @return null
 **/
function array_to_csv_download(array &$array) {
    
    if (count($array) == 0) {
        return null;
    }
    
    $filename = "data_export_" . date("Y-m-d") . ".csv";
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");

    // force download  
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");

    // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");

    $df = fopen("php://output", 'w');
    fputcsv($df, array_keys(reset($array)));
    foreach ($array as $row) {
        fputcsv($df, $row);
    }
    fclose($df);
    die();    
}

Note that above function should be called before any headers are sent to the browser. In simple words call to the above function should occur before the <html>  tag. So code for an example php file using the above function is given below.

$db_recordset = array(
                    array('id'=>'560','name'=>'John','age'=>'31','occupation'=>'Designer'),
                    array('id'=>'561','name'=>'Robert','age'=>'21','occupation'=>'Student')
                );
                
array_to_csv_download($db_recordset);

Leave a Reply

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