I want to export CSV file in Laravel but it returns only text.
$(document).on("click","#csvIcon",function(){
$('#mask').css('display','block');
var fId=$(this).attr('data-formId');
$.get('/clientarea/form/responses/csv/export',
{'formId':fId},
function (data,status,xhr) {
$('#mask').css('display','none');
}
)
});
route:
Route::get('/clientarea/form/responses/csv/export',[ResponsesController::class,'exportCsv']);
My controller: In the controller I have to array $data and $questions that fetched from database to create my csv content.
public function exportCsv(Rrequest $request)
...
$data=['a','b','c','d'];
$questions=['s1','s2','s3','s4'];
function cleanData(&$str)
{
if(preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
$str = "'$str";
}
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
$fileName = "form_data_" . date('Ymd') . ".csv";
$headers = array(
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=$fileName",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0"
);
$callback = function() use($data, $questions) {
$file = fopen('php://output', 'w');
array_walk($questions, __NAMESPACE__ . '\cleanData');
fputcsv($file, $questions,',', '"');
foreach ($data as $row)
{
array_walk($row, __NAMESPACE__ . '\cleanData');
fputcsv($file, $row,',', '"');
}
fclose($file);
};
return response()->stream($callback, 200, $headers);
}
It returns for example:
s1,s2,s3,s4
a,b,c,d
instead of the csv file to download