我正在try 使用Laravel将数据库表导出为csv文件.我希望用户能够 Select Export as CSV按钮并将表格下载为csv文件.目前我已获得此代码,但它不起作用:

我的按钮:

<a href="/all-tweets-csv" class="btn btn-primary">Export as CSV</a>

my route:

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

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);

You should change this line into:

return Response::download($filename, 'tweets.csv', $headers);

Laravel相关问答推荐

密码确认在Livewire中不匹配

使用Laravel判断其他数据库中是否存在记录

如何解决此 Backblaze B2 S3 兼容 API 错误?

嵌套数组请求的 Laravel 验证,其中如果整数之一为零,则另一个应大于零

Laravel查询多对多关系

如何在自引用表上使用 Laravel 的 hasManyThrough

找不到 Laravel 5 类日志(log)

Laravel - 如果值包含某个字符串(取自搜索输入),则查询模型

Laravel 5.8 在从已清除的会话中单击注销后显示419 Page Expired

Laravel/Eloquent:致命错误:在非对象上调用成员函数 connection()

如何在 Laravel 4 中使用没有 id 的 Eloquent 更新数据

需要 Vagrant 环境或目标机器

使用模型工厂、一对一和一对多关系定义 Laravel 外键,而不创建不必要的模型

如何使用外部图像生成 html div 的 screenshot截图?

PHP Laravel:如何获取客户端浏览器/设备?

Laravel 中的填充方法不起作用?

如果 Laravel 中的值不为空,如何验证输入字段

Laravel Eloquent 查询生成器默认 Where 条件

Laravel 4 简单路由无法使用 mod_rewrite 和 .htaccess

在laravel中删除确认