====== 【Laravel】CSVダウンロード(エクスポート) ======
Laravel で CSV ダウンロード機能を実装する一例。
===== App\Http\Controllers\CsvController.php =====
文字コードを SJIS で出力する場合の例。\\
==== まとめて文字コードを UTF-8 から SJIS(CP932) に変換する例 ====
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;
}
}
==== 1行毎に文字コードを UTF-8 から SJIS-win に変換する例 ====
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']
);
}
}