4

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

3 回答 3

19

使用这个片段应该做你想做的事情。

<?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;
    }
?>
于 2012-06-01T04:45:31.187 回答
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;
于 2012-06-01T04:18:28.093 回答
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);
于 2014-05-19T06:31:21.233 回答