このページの2つのバージョン間の差分を表示します。
プログラム言語:php:laravel:csvダウンロード [2021/02/25 17:27] humolife 作成 |
プログラム言語:php:laravel:csvダウンロード [2022/09/29 11:46] (現在) humolife [App\Http\Controllers\CsvController.php] |
||
---|---|---|---|
行 2: | 行 2: | ||
Laravel で CSV ダウンロード機能を実装する一例。 | Laravel で CSV ダウンロード機能を実装する一例。 | ||
===== App\Http\Controllers\CsvController.php ===== | ===== App\Http\Controllers\CsvController.php ===== | ||
- | 文字コードを SJIS-win で出力場合の例。\\ | + | 文字コードを SJIS で出力する場合の例。\\ |
+ | ==== まとめて文字コードを UTF-8 から SJIS(CP932) に変換する例 ==== | ||
< | < | ||
class CsvController extends Controller | class CsvController extends Controller | ||
{ | { | ||
- | public function download(Survey | + | public function download() |
+ | { | ||
+ | | ||
+ | |||
+ | $response = new StreamedResponse(function () use ($users) { | ||
+ | $stream = fopen(' | ||
+ | |||
+ | stream_filter_prepend($stream, | ||
+ | |||
+ | fputcsv($stream, | ||
+ | ' | ||
+ | ]); | ||
+ | |||
+ | foreach ($user as $key => $user) { | ||
+ | fputcsv($stream, | ||
+ | $user-> | ||
+ | $user-> | ||
+ | $user-> | ||
+ | ]); | ||
+ | } | ||
+ | |||
+ | fclose($stream); | ||
+ | }); | ||
+ | |||
+ | $file_name = ' | ||
+ | |||
+ | $response-> | ||
+ | $response-> | ||
+ | |||
+ | return $response; | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | ==== 1行毎に文字コードを UTF-8 から SJIS-win に変換する例 ==== | ||
+ | < | ||
+ | class CsvController extends Controller | ||
+ | { | ||
+ | public function download() | ||
{ | { | ||
$csv_headers = [' | $csv_headers = [' | ||
行 14: | 行 53: | ||
return response()-> | return response()-> | ||
- | function () use ($survey, | + | function () use ($csv_headers, |
$stream = fopen(' | $stream = fopen(' | ||