Skip to content

Instantly share code, notes, and snippets.

@ajcarrillo
Created February 4, 2021 04:41
Show Gist options
  • Save ajcarrillo/c7fe8cea9ad6e1cf4d478b65ec326dc6 to your computer and use it in GitHub Desktop.
Save ajcarrillo/c7fe8cea9ad6e1cf4d478b65ec326dc6 to your computer and use it in GitHub Desktop.

Revisions

  1. @albofish albofish renamed this gist Jul 9, 2014. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. @albofish albofish revised this gist Jul 9, 2014. 1 changed file with 14 additions and 13 deletions.
    27 changes: 14 additions & 13 deletions gistfile1.php
    Original file line number Diff line number Diff line change
    @@ -3,21 +3,22 @@
    * 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");
    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);
    $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);
    }
    $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');
  3. @albofish albofish created this gist Jul 9, 2014.
    25 changes: 25 additions & 0 deletions gistfile1.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    <?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);