このページの2つのバージョン間の差分を表示します。
次のリビジョン | 前のリビジョン | ||
プログラム言語:php:laravel:csvダウンロード [2021/02/25 17:27] humolife 作成 |
プログラム言語:php:laravel:csvダウンロード [2024/11/06 08:47] (現在) humolife [1行毎に文字コードを UTF-8 から SJIS-win に変換する例] |
||
---|---|---|---|
行 2: | 行 2: | ||
Laravel で CSV ダウンロード機能を実装する一例。 | Laravel で CSV ダウンロード機能を実装する一例。 | ||
===== App\Http\Controllers\CsvController.php ===== | ===== App\Http\Controllers\CsvController.php ===== | ||
- | 文字コードを SJIS-win で出力場合の例。\\ | + | 文字コードを SJIS で出力する場合の例。\\ |
+ | ==== まとめて文字コードを UTF-8 から SJIS(CP932) に変換する例 ==== | ||
+ | < | ||
+ | use Symfony\Component\HttpFoundation\StreamedResponse; | ||
+ | |||
+ | class CsvController extends Controller | ||
+ | { | ||
+ | public function download() | ||
+ | { | ||
+ | $users = Users:: | ||
+ | |||
+ | $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 | class CsvController extends Controller | ||
{ | { | ||
- | public function download(Survey $survey) | + | public function download() |
{ | { | ||
$csv_headers = [' | $csv_headers = [' | ||
行 14: | 行 55: | ||
return response()-> | return response()-> | ||
- | function () use ($survey, | + | function () use ($csv_headers, |
$stream = fopen(' | $stream = fopen(' | ||