0
1

More than 1 year has passed since last update.

Laravel CSVダウンロード

Posted at

共通関数にでもしておき引数渡してダウンロード

$csv = [
            ['id','user'],
            [1,'a'],
            [2,'b']
        ];

$file_name = 'CSV' . date('YmdHis');
$response = Csv::csv_download($csv, $file_name);
return $response;
<?php

namespace App\Library;

use Illuminate\Support\Facades\Facade;
use Symfony\Component\HttpFoundation\StreamedResponse;

class Csv extends Facade
{
    public static function csv_download($data, $fileName)
    {
        $response = new StreamedResponse(function () use ($data) {
            $stream = fopen('php://output', 'w');

            // 文字化け回避
            stream_filter_prepend($stream, 'convert.iconv.utf-8/cp932//TRANSLIT');

            // データからcsv生成
            foreach ($data as $key => $value) {
                fputcsv($stream, $value);
            }
            fclose($stream);
        });

        $response->headers->set('Content-Type', 'application/octet-stream');
        $response->headers->set('Content-Disposition', 'attachment; filename="' . $fileName . '.csv"');

        return $response;
    }
}

0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1