我对CSV下载有些困惑。我很高兴把它保存到一个文件中,并提供给用户一个链接,但从情况来看,这似乎是错误的做法
like
these
.
从这个答案出发
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()
似乎是合乎逻辑的选择,但这给了我以下错误:
类Closure的对象无法转换为字符串
这很有道理。正确的方法是什么?或者我应该保存文件,然后只使用文件路径作为我的
下载()
功能似乎是坏习惯?