下载 CSV 文件


download csv file

当我们单击该按钮时,我们有一个按钮,所有数据都会进入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;

使用此代码段应该做您正在尝试做的事情。

<?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;
    }
?>

您无需将文件保存到磁盘,只需在设置适当的标头后回显 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;
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);