【发布时间】:2016-10-11 04:28:54
【问题描述】:
我对 CSV 下载有点困惑。我很高兴将其保存到文件中并向用户提供链接,但从 likethese 的事情来看,这似乎是错误的方法。
从这个答案Use Laravel to Download table as CSV 开始,我想我发现stream() 方法不再存在。
public function download()
{
$headers = [
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0'
, 'Content-type' => 'text/csv'
, 'Content-Disposition' => 'attachment; filename=galleries.csv'
, 'Expires' => '0'
, 'Pragma' => 'public'
];
$list = $this->users->getAllUsers()->toArray();
# add headers for each column in the CSV download
array_unshift($list, array_keys($list[0]));
$callback = function() use ($list)
{
$FH = fopen('php://output', 'w');
foreach ($list as $row) {
fputcsv($FH, $row);
}
fclose($FH);
};
// return Response::stream($callback, 200, $headers); // Old version
return response()->download($callback, 'Users-' . date('d-m-Y'), $headers);
}
我尝试使用 Laravel 5.2 response() 函数,但是我对我的回应有点迷茫 - download() 似乎是合乎逻辑的选择,但这给了我以下错误:
闭包类的对象无法转换为字符串
这是有道理的。这样做的正确方法是什么?或者我应该保存文件,然后只使用文件路径作为我的download() 函数的第一个参数——这似乎是不好的做法?
【问题讨论】:
标签: php download laravel-5.2