Skip to content

Instantly share code, notes, and snippets.

@hemantachhami19
Forked from paligiannis/outputCSV.php
Created May 14, 2020 15:50
Show Gist options
  • Save hemantachhami19/76a286f45cf548eb33f757e198f73a62 to your computer and use it in GitHub Desktop.
Save hemantachhami19/76a286f45cf548eb33f757e198f73a62 to your computer and use it in GitHub Desktop.
Laravel Chunk Results to CSV
<?php
/*
* Chunk through result set and output as CSV file in browser.
*/
function outputCSV($columns, $query, $chunkSize = 200) {
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename='export-" . date("YmdHis") . ".csv");
header("Pragma: no-cache");
header("Expires: 0");
$output = fopen("php://output", "w");
fputcsv($output, $columns);
$query->select($columns)->chunk($chunkSize, function($rows) use(&$output) {
foreach ($rows as &$row) {
fputcsv($output, (array) $row);
}
});
fclose($output);
}
// Eloquent or Fluent DB query
$query = DB::table('users');
$columns = ['id', 'name', 'email'];
outputCSV($columns, $query);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment