下载CSV文件

4
我们有一个按钮,当我们点击该按钮时,所有的数据会被放入 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;

你的文件里为什么有这么多变量呢?无论如何,我认为这篇文章 http://stackoverflow.com/questions/1487774/generating-csv-file-and-then-forcing-the-file-to-download 可以解决你的问题。 - Saurabh Kumar
可选地,您还可以查看http://php.net/manual/en/function.readfile.php。 - Saurabh Kumar
如果有一个可接受的答案,请将其标记为答案。 - Andrew Atkinson
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;
    }
?>

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;

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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接