从服务器下载CSV文件

时间:2012-12-31 21:55:52

标签: php csv

我正在查询我的数据库并使用结果创建一个csv文件。然后我将前端页面上的链接放到服务器上创建的文件中,如下所示:

function writetofile($stringData, $myFile) {
     $fh = fopen('download/'.$myFile, 'w') or die("can't open file");
     fwrite($fh, $stringData);
     fclose($fh);
}

$filename = $file."_".date("d-m-Y_H-i",time()).'.csv';

writetofile($seperator, $filename);
print 'Right-click on the link below and select "Save as":' . '<br/><br/>';
print 'Download File: <a href="/download/'.$filename.'" target="_blank">Download Link</a>'; 

出于某种原因,当我直接从服务器下载文件时,它看起来与db中的所有行一致。但是,当我完成用户将要执行的操作的步骤,即右键单击并保存时,该文件仅包含此页面中的html代码。

1 个答案:

答案 0 :(得分:4)

更新查看http://php.net/manual/en/function.readfile.php

放入合适的php标头,输出文件内容并退出:

<?php // none space here
function writetofile($stringData, $myFile)
{
    if ( ! file_exists('download/' . $myFile))
    {
        echo 'file missing';
    }
    else
    {
        header('HTTP/1.1 200 OK');
        header('Cache-Control: no-cache, must-revalidate');
        header("Pragma: no-cache");
        header("Expires: 0");
        header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename=$myFile");
        readfile('download/' . $myFile);
        exit;
    }
}

无论如何调查http://php.net/manual/en/function.fputcsv.php以确保正确的csv格式化......

相关问题