php 在laravel导出数据(1000+记录)在CSV没有任何包?

hk8txs48  于 5个月前  发布在  PHP
关注(0)|答案(1)|浏览(77)

当点击ExportCSV路由时,它会在浏览器上显示所有数据,而不是(下载)导出CSV文件。

控制器:

public function export()
    {
        $datas = DeviceStorage::all();
        $csvFileName = 'min_value.csv';
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $csvFileName . '"',
        ];

        $handle = fopen('php://output', 'w');
        fputcsv($handle, ['device_id', 'device_name' , 'min_sale_price']); 

        foreach ($datas as $data) {
            fputcsv($handle, [$data->device_id, $data->Device->device_name, $data->min_sale_price]); 
        }

        fclose($handle);

        return Response::make('', 200, $headers);
    }

字符串

路线:

Route::get('export/csv' , [DeviceController::class , 'export'])->name('export.csv');

刀片文件:

<a class="btn btn-primary" href="{{ url('export/csv') }}">Export CSV</a>

elcex8rz

elcex8rz1#

要解决这个问题,请按照以下步骤操作:

public function exportCsv()
    {
        $data = YourModel::all();

        $csvFileName = 'export.csv';
        $headers = array(
            "Content-type"        => "text/csv",
            "Content-Disposition" => "attachment; filename=$csvFileName",
            "Pragma"              => "no-cache",
            "Cache-Control"       => "must-revalidate",
            "Expires"             => "0",
        );

        $handle = fopen('php://output', 'w');

        // Add CSV header
        fputcsv($handle, array_keys($data->first()->toArray()));

        // Add CSV rows
        foreach ($data as $row) {
            fputcsv($handle, $row->toArray());
        }

        fclose($handle);

        return response()->stream(
            function () use ($handle) {
                fclose($handle);
            },
            200,
            $headers
        );
    }

字符串

相关问题