我使用PHP生成一个JSON文件,通过标题,我会在文件生成完成后立即下载它。当我运行下面的代码时,我会查看我的" downloads"文件夹和下载文件的扩展名不是" .json"但是" .json.html"。
如何保留文件的扩展名" .json"?
这是我的代码:
foreach($tickets as $ticket)
{
$data['tickets'][] = [
'tickets_id' => $ticket->ticket_id,
'name' => strtolower($ticket->name),
'email' => strtolower($ticket->email),
'status' => $ticket->status
];
}
header('Content-Type: application/json');
header('Content-Disposition: attachment; filename=db.json');
header('Pragma: no-cache');
echo json_encode($data);
下载的文件是=> db.json.html 不 db.json
编辑:以下完整代码
public function ticketsExportJSON($id)
{
$tickets = Ticket::where('event_id', $id)->with('event')->get();
$data = [];
$i = 0;
foreach($tickets as $ticket)
{
$i++;
if($i == 1)
{
$data = [
'event' => $ticket->event->title,
'date' => $ticket->event->event_date
];
}
else
{
$data['tickets'][] = [
'tickets_id' => $ticket->ticket_id,
'name' => strtolower($ticket->name),
'email' => strtolower($ticket->email),
'status' => $ticket->status
];
}
}
header('Content-Type: application/json');
header('Content-Disposition: attachment; filename=db.json');
header('Pragma: no-cache');
echo json_encode($data);
}
使用路由:/ download / json来调用ticketsExportJSON函数。
答案 0 :(得分:0)
通过传递streamDownload()
作为第三个参数,只需使用[ 'Content-Type' => 'application/json' ]
方法(https://laravel.com/docs/7.x/responses#file-download)。
答案 1 :(得分:-1)
我认为您忘记在代码末尾添加exit();
。