-
-
Save paligiannis/ebe67628c39e2bb5e2576c30ebb68726 to your computer and use it in GitHub Desktop.
Laravel Chunk Results to CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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