Use Laravel to Download table as CSV(使用 Laravel 将表格下载为 CSV)
问题描述
我正在尝试使用 Laravel
作为 csv
文件导出数据库表.我希望用户能够选择 Export as CSV
按钮并将表格下载为 csv
文件.目前我已经得到了这个代码,但它不起作用:
I am trying to export a database table using Laravel
as a csv
file. I would like the user to be able to select the Export as CSV
button and download the table as a csv
file. Currently I've gotten this code but It is not working:
我的按钮:
<a href="/all-tweets-csv" class="btn btn-primary">Export as CSV</a>
我的路线:
Route::get('/all-tweets-csv', function(){
$table = Tweet::all();
$filename = "tweets.csv";
$handle = fopen($filename, 'w+');
fputcsv($handle, array('tweet text', 'screen name', 'name', 'created at'));
foreach($table as $row) {
fputcsv($handle, array($row['tweet_text'], $row['screen_name'], $row['name'], $row['created_at']));
}
fclose($handle);
$headers = array(
'Content-Type' => 'text/csv',
);
return Response::download($handle, 'tweets.csv', $headers);
});
它返回给我这个错误:
The file "Resource id #154" does not exist
我发现这是因为它正在尝试下载一个不存在的文件.是否有另一种方法可以修改我的代码以便下载为 csv
.
And I've gathered that it is because it is trying to download a file that does not exist. Is there an alternative way I can go about modifying my code in order to download as a csv
.
推荐答案
除了这一行,几乎一切都好:
Almost everything is fine except this line:
return Response::download($handle, 'tweets.csv', $headers);
您应该将此行更改为:
return Response::download($filename, 'tweets.csv', $headers);
这篇关于使用 Laravel 将表格下载为 CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Laravel 将表格下载为 CSV


基础教程推荐
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何替换eregi() 2022-01-01