Laravel 5.7ã§CSVããã¦ã³ãã¼ãããã¨ãã«å 容ãç»é¢ã«è¡¨ç¤ºããã¦ãã¾ã
Laravel 5.7ã§CSVããã¦ã³ãã¼ãããã¨ãã«å 容ãç»é¢ã«è¡¨ç¤ºããã¦ãã¾ã
CSVãã¡ã¤ã«ããã¦ã³ãã¼ãããæ©è½ã®ä½æãä¾é ¼ãã¦ãã¦ã
質åããããåå ãå
¨ç¶åãããªãã£ãã
ç°å¢
ç¾è±¡
ä¸å®ã¾ã§ã®ãµã¤ãºãªãCSVãã¡ã¤ã«ããã¦ã³ãã¼ãããããã
ä¸å®ã®ãµã¤ãºãè¶
ããã¨å
容ãç»é¢ã«è¡¨ç¤ºãããã
ã¨ããããã¡ã¢ãªãªã¼ã¯ãã¦ãï¼ã¨ã¯æã£ãããä»åã®åé¡ã«ã¯é¢ä¿ãªãã®ã§è§¦ããªãã§ãããã
åé¡ã®ã³ã¼ã
public function csvDownload(Request $request) { $headers = [ 'Content-Type' => 'text/csv', 'Content-Disposition' => 'attachment; filename="users.csv"' ]; $stream = csvDownload($request); // æ¤ç´¢ãã¦streamã«æ¸ãè¾¼ã return \Response::make(stream_get_contents($stream), 200, $headers); }
åå
ä¸è¨ã®åèãã¼ã¸ãçºè¦ãã¦ç¥ã£ããããããªä»æ§ããããããã
æå¾ã«ãHttpãããã¼ã®ä½æã¾ã§ã«æéãããããããã£ã¦ãã¾ã£ãå ´åããããããã¡ã¤ã«ã®ãã¦ã³ãã¼ãã«å¤±æãã¦ãã¾ãã¾ãã
ããã¯ããã©ã¦ã¶ããã°ããã¬ã¹ãã³ã¹ãå¾ ã£ã¦ãHttpãããã¼ãè¿ã£ã¦ããªãå ´åãããã©ã«ãã®ãããã¼ã使ã£ã¦ãã©ã¦ã¶ã«ãã¼ã¿ãåãåºãã¦ãã¾ãã¨ããä»æ§ã«ãããã®ã§ãã
対å¿
åèãã¼ã¸ã«ä¹ã£ã¦ããã³ã¼ããä¸é¨æ¹å¤ã使ç¨ããã
å¤æ´ç¹
- BOMã®ä»ãæ¹ãå ã®ããæ¹ã§ã¯æååã¨ãã¦åºåãããããå¤æ´
- ãã¹ããæµ ããªãã®ã§chunkããcursorã«å¤æ´
use \Symfony\Component\HttpFoundation\StreamedResponse; public function csvDownload(Request $request) { $headers = [ 'Content-Type' => 'text/csv', 'Content-Disposition' => 'attachment; filename="users.csv"' ]; return new StreamedResponse( function () { $stream = fopen('php://output', 'w'); // Excelã§UTF-8ã¨èªèãããããã«BOMãä»ãã(å¤æ´é¨å) fwrite($stream, pack('C*', 0xEF, 0xBB, 0xBF)); // chunkã§ã¯ãªãcursorã使ç¨(å¤æ´é¨å) $cursor = \DB::table("users")->orderBy("id")->cursor(); foreach ($cursor as $user) { fputcsv($stream, [$user->id, $user->name]); } fclose($stream); }, 200, $headers ); }