Laravel で CSV ダウンロード機能を実装する一例。
文字コードを SJIS で出力する場合の例。
use Symfony\Component\HttpFoundation\StreamedResponse; class CsvController extends Controller { public function download() { $users = Users::get(); $response = new StreamedResponse(function () use ($users) { $stream = fopen('php://output', 'w'); stream_filter_prepend($stream, 'convert.iconv.utf-8/cp932//TRANSLIT'); fputcsv($stream, [ 'ID', '名前', 'メールアドレス' ]); foreach ($user as $key => $user) { fputcsv($stream, [ $user->id, $user->name, $user->email, ]); } fclose($stream); }); $file_name = 'ファイル名.csv'; $response->headers->set('Content-Type', 'application/octet-stream'); $response->headers->set('content-disposition', 'attachment; filename=' . $file_name); return $response; } }
class CsvController extends Controller { public function download() { $csv_headers = ['No.', 'Name', 'Date']; $csv_body = []; // DB からデータを読み込むなどし csv_body に格納 return response()->streamDownload( function () use ($csv_headers, $csv_body) { $stream = fopen('php://output', 'w'); mb_convert_variables('SJIS-win', 'UTF-8', $csv_headers); fputcsv($stream, $csv_headers); foreach ($csv_body as $line) { mb_convert_variables('SJIS-win', 'UTF-8', $line); fputcsv($stream, $line); } fclose($stream); }, 'file_name.csv', ['Content-Type' => 'application/octet-stream'] ); } }
コメント