Lal Kumar Rai
Lal Kumar Rai

Reputation: 343

Generate csv file using laravel

I searched in google to generate the csv file from laravel and i have found the following code:

  public function download(){
  $headers = [
    'Cache-Control'       => 'must-revalidate, post-check=0, pre-  check=0'
    ,   'Content-type'        => 'text/csv'
    ,   'Content-Disposition' => 'attachment; filename=galleries.csv'
    ,   'Expires'             => '0'
    ,   'Pragma'              => 'public'
   ];

$list = User::all()->toArray();

# add headers for each column in the CSV download
array_unshift($list, array_keys($list[0]));

$callback = function() use ($list) 
{
    $FH = fopen('php://output', 'w');
    foreach ($list as $row) { 
        fputcsv($FH, $row);
    }
    fclose($FH);
 };

return Response::stream($callback, 200, $headers);
}

In the above code, i didn't understand

$callback = function() use ($list){...}

will someone please explain me?

Upvotes: 3

Views: 5976

Answers (2)

Rob
Rob

Reputation: 1280

I've recently discovered the 'league/csv' package - have written a S.O post about my usage (a simple example) here: CSV export in laravel 5 controller

Upvotes: 0

Matt
Matt

Reputation: 1131

Save yourself a world of trouble and use this library: http://www.maatwebsite.nl/laravel-excel/docs

It can convert your data to csv, excel and all other sorts of goodies. It's especially good with larger datasets.

Cause it's all fun and games when you open your csv in the same program on the same OS. But as soon as your client uses Libre, Open or just Office op MS or Mac your world will go to new depths of hell in multiple layers.

This library standardises csv for as far as possible and you will love it.

Upvotes: 2

Related Questions