Downloading/Populating 使用 SendFile 的 CSV 文件

Downloading/Populating CSV File with SendFile

我正在使用 PHP Yii 框架并尝试下载我的文件。目前,它会下载,但文件会填充 $filePath 位置。为什么这不能正确填充我的文件?

$getData = // Getting data here.

$fileName = "file.csv";

$filePath = __Dir__ . "/.../exports";
$file = fopen($filePath . '' . $fileName, "w");
fputcsv($file, array_keys($getData[0]));
foreach ($getData as $row){
    fputcsv($file, $row);
}

    header("Content-Type: text/plain");
    header("Content-disposition: attachment; filename = $fileName");
    header("Pragma: no-cache");
    Yii::app()-> request -> sendFile($fileName, $filePath);

两件事。第一,我认为您在 $filePath$fileName 变量之间缺少 /。不应该是这样的:

$file = fopen($filePath . '/' . $fileName, "w");

其次,我认为您调用 sendFile() 的方式不正确。第二个参数不应是文件的路径。相反,它应该是应该发送到浏览器的实际内容。因此,请尝试将该行更改为:

Yii::app()->request->sendFile($fileName,  file_get_contents($filePath . '/' . $fileName));

此处,在第二个参数中,我们提供 $filePath . '/' . $fileName 指定路径中的文件内容。

经过进一步研究,我能够解决我的错误。我需要添加 file_get_contents 而不是它的实际路径。

原文:

Yii::app()-> request -> sendFile($fileName, $filePath); 

修改:

Yii::app()-> request -> sendFile($fileName, file_get_contents($filePath . "/" . $fileName));