Skip to content

Instantly share code, notes, and snippets.

@paligiannis
Forked from albofish/outputCSV.php
Created November 20, 2019 11:20
Show Gist options
  • Save paligiannis/ebe67628c39e2bb5e2576c30ebb68726 to your computer and use it in GitHub Desktop.
Save paligiannis/ebe67628c39e2bb5e2576c30ebb68726 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