Export Array to CSV File and Download

Written by @kerixa 1 September 2020

If you are using data and analyze them in your website, you may need to export them in a CSV file. The following function shows how to implement this job and download the exported CSV file automatically.

Code Snippet:

                                                
                                                <!-- this script is provided by https://www.phpfreecode.com coded by: Kerixa Inc. -->
<?php
$myarray = array(
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
    );

download_send_headers("data_export_" . date("Y-m-d") . ".csv");
echo array2csv($myarray);
die();


function download_send_headers($filename) {
    // 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");
}

function array2csv(array &$array){
   if (count($array) == 0) {
     return null;
   }
   ob_start();
   $df = fopen("php://output", 'w');
   fputcsv($df, array_keys($array));
   foreach ($array as $row) {
      fputcsv($df, $row);
   }
   fclose($df);
   return ob_get_clean();
}
?><a target='_blank' href='https://www.phpfreecode.com' style='font-size: 8pt; text-decoration: none'>Php Best Codes</a>                                                
                                            

Example:


About @kerixa

I am Krishna Eydat. I studied Software Engineering at University of Waterloo in Canada. I lead a few tech companies. I am passionate about the way we are connected. I would like to be part of something big or be the big deal!

K

Comments


Here you can leave us commments. Let us know what you think about this code tutorial!

0 / 300

TRENDING POST
1
2
3
4
5
VISITORS
Online Users: 12
Recent Members: grkkid, Manaakividuinfo.com, karticksv, sava, tinatina
advertisement 2