1.fopenして、fputcsvで作成する手法。
public function csv(){ $ary = [ ["山田", "12", "O",""], ["田中", "20", "A",""], ["吉田", "18", "AB",""], ["伊藤", "19", "B", "エンジニア"] ]; foreach($ary as $key => $value){ array_splice($ary[$key], 1, 0, ""); } $column = ["名前", "無記入", "年齢", "血液型", "備考"]; array_unshift($ary, $column); $filename = "hogehoge.csv"; $f = fopen($filename, "w"); stream_filter_prepend($f,'convert.iconv.utf-8/cp932'); if($f) { foreach($ary as $line){ fputcsv($f, $line); } } header('Content-Type: application/octet-stream'); header('Content-Length: '.filesize($filename)); header('Content-Disposition: attachment; filename=hogehoge.csv'); readfile($filename); }
2. StreamedResponseを使う書き方
public function csv(){ $data = User::all(); $response = new StreamedResponse(function() use($data){ $stream = fopen('php://output', 'w'); stream_filter_prepend($stream, 'convert.iconv.utf-8/cp932//TRANSLIT'); fputcsv($stream, ['id','name','email',]); foreach($data as $user){ fputcsv($stream, [$user['id'],$user['name'],$user['email'],]); } fclose($stream); }); $response->headers->set('Content-Type', 'application/octet-stream'); $response->headers->set('Content-Disposition', 'attachment; filename="user.csv"'); return $response; }
やってることは一緒なんだけど、StreamedResponseの方が良い。