Export/Download data as a csv file

 
<?php

$csv_data = array();
$csv_data[] = array(
    'col 1',
    'col 2',
    'col 3',
);
$csv_data[] = array(
    'data 1',
    'data 2',
    'data 3',
);
$csv_data[] = array(
    'data 1',
    'data 2',
    'data 3',
);

$file_name = 'file.csv';

header('Pragma: public');
header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: pre-check=0, post-check=0, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');
header('Content-Transfer-Encoding: none');
header('Content-Type: application/vnd.ms-excel');
header('Content-Type: application/x-msexcel');
header('Content-Disposition: attachment; filename="' . $file_name . '"');

$fp = fopen('php://output', 'w');
if ($fp) {
    foreach ($csv_data as $fields) {
        fputcsv($fp, $fields);
    }

    fclose($fp);
}

 

Related Snippets

•  File Upload Form
•  Export data to a csv file