This is for csv file create and force download for that file.
This working but I need to know is it doing correct way.
public function exportCSV($results){
try {
$filename = CSV_PATH.'file.csv';
$numRows = count($results);
$handle = fopen($filename, 'w+') or die("can't open file");
fputcsv($handle, array('id','name','age','address'));
foreach ($results as $row) {
fputcsv($handle, $row);
}
fclose($handle);
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($filename));
header('Connection: close');
readfile($filename);
exit();
} catch(Exception $e) {
echo $e->getMessage();
}
}
CSV_PATH is on config.php file
use string rather then file writing it causes lot of overhead.
$out = "";
$out .= implode(",", array('id','name','age','address')) . "\r\n";
foreach ($results as $row) {
$out .= implode(",", $row) . "\r\n";
}
now do same .
....
header('Connection: close');
echo $out;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.