当我们点击该按钮时,我们有一个按钮,所有数据都会进入csv文件并下载此csv文件。 csv文件创建但下载代码无法正常工作
$fp = fopen("file\customer-list.csv", "w");
fileName = "file\customer-list.csv";
$filePath = "file\customer-list.csv";
$fsize = filesize("file\customer-list.csv");
if(($_POST['csv_download_list']) == "cm")
{
fwrite($fp, $csv);
fclose($fp);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=\"$fileName\"");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Length: ' . filesize($filePath));
ob_clean();
flush();
$file = @fopen($filePath,"rb");
if ($file) {
while(!feof($file)) {
print(fread($file, 1024*8));
flush();
}
@fclose($file);
}
exit;
答案 0 :(得分:17)
使用此代码段应该执行您要执行的操作。
<?php
$file = 'sample.csv'; //path to the file on disk
if (file_exists($file)) {
//set appropriate headers
header('Content-Description: File Transfer');
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
//read the file from disk and output the content.
readfile($file);
exit;
}
?>
答案 1 :(得分:3)
您无需将文件保存到磁盘,只需在设置适当的标头后回显csv内容即可。 尝试下面的代码,它会更简单
$fileName = 'customer-list.csv';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $fileName);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
echo $csv;
exit;
答案 2 :(得分:0)
Try...
function download($file) {
if (!file_exists($file)) {
return false;
}
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Length: ' . filesize($file));
readfile($file);
exit();
}
$file = "file.csv";
download($file);