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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With