导出CSV响应laravel 5.5并下载为CSV文件 [英] Exporting CSV response laravel 5.5 and download as csv file
本文介绍了导出CSV响应laravel 5.5并下载为CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用ajax请求导出并下载csv文件中的某些数据.我能够将数据输出到json响应中进行测试,但无法将其下载到data.csv文件中
I am trying to export and download some data in a csv file using an ajax request. I was able to output the data in a json response to test but could not get it to download in a data.csv file
public function download(Request $request)
{
if(!empty($request->input('my_checkbox')))
{
$studentIdToExportArray = $request->input('my_checkbox');
//$msg = is_array($studentIdToExportArray);//returns true
$selectedStudents = [];
foreach($studentIdToExportArray as $student_id)
{
$student = Students::find($student_id);
array_push($selectedStudents, $student);
}
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output=fopen("php://output","w");
fputcsv($output,array("ID","firstname","surname","email","nationality","address_id","course_id"));
foreach($selectedStudents as $s1)
{
$array = json_decode(json_encode($s1), true);
fputcsv($output, $array);
}
fclose($output);
return response()->json([
'test'=> $selectedStudents
]);
}
}
控制台中输出响应的屏幕截图
问题:data.csv文件未下载
Problem: The file data.csv does not download
推荐答案
尝试:
$file=fopen('../storage/app/test.csv','w');
$headers = array(
'Content-Type' => 'text/csv',
);
$path = storage_path('test.csv');
return response()->download($path, 'test.csv', $headers);
这篇关于导出CSV响应laravel 5.5并下载为CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文