In web development, often we need to export data in a structured format that can be easily imported into other applications. CSV (Comma-Separated Values) is a popular choice for this, and Laravel, a robust PHP framework, provides efficient ways to generate and download CSV files on the fly. In this article, we'll explore how to leverage Laravel's powerful features to create and download dynamic CSV files.
Set the filename for csv file
$csvFileName = 'custom-data.csv';
Set header for client webbrowser
$headers = [
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="' . $csvFileName . '"',
'Expires' => '0',
'Pragma' => 'public'
];
Generate random data
$data= [];
for ($i=0;$i<100;$i++) {
$data[] = [
mt_rand(1, 100),
mt_rand(1, 100),
mt_rand(1, 100)
];
}
Creating csv file on the fly
$callback = function () use ($data)
{
$handle = fopen('php://output', 'w');
foreach ($data as $value) {
fputcsv($handle, $value);
}
fclose($handle);
};
return response()->stream($callback, 200, $headers);