3

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?

3
  • It's creating a callback function and assigning that function to a variable; that variable is then being passed as an argument to Response::stream() and Response::stream() will be able to execute that function Commented Apr 12, 2016 at 9:10
  • 1
    I'd strongly recommend using Laravel Excel - maatwebsite.nl/laravel-excel/docs It provides a nice wrapper for the functionality you are looking for. Commented Apr 12, 2016 at 9:12
  • thank you for your great opinions Commented Apr 12, 2016 at 9:22

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.