It's free and you have access to premium codes!
Welcome back! Please login to your account.
Don't worry, we'll send you a message to help you to recover your acount.
Please check your email for instructions to activate your account.
Written by 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.
<!-- 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>
Comments
Here you can leave us commments. Let us know what you think about this code tutorial!