[英]PhpSpreadsheet return file instead of saving it
我已經生成了 xmlx 文件,我可以保存它並通過以下方式提供給用戶:
$writer->save('hello world.xlsx');
header('Location: hello world.xlsx');
但是,該文件仍保留在硬盤驅動器上。 我需要擺脫它,因為它是一個安全威脅。
我嘗試取消鏈接文件
unlink('hello world.xlsx');
但這會過早地刪除文件,因此用戶無法訪問它。 如果它可以與 unlink 一起工作,那么我需要確保該文件將被刪除(因此正確使用die();
等)
編輯:這不僅僅是出於安全原因。 提供程序不允許保存文件,因此這是唯一的方法。
使用php://output
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="file.xls"');
$writer->save("php://output");
您可以在文件創建后直接發送文件,而不是重定向到文件。
$filename = 'hello world.xlsx';
$writer->save($filename);
// Set the content-type:
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Length: ' . filesize($filename));
readfile($filename); // send file
unlink($filename); // delete file
exit;
ob_end_clean();
$writer->save('php://output');
您可以使用內存文件指針並從中讀取。
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$fp = fopen("php://memory", "rw");
$writer->save($fp);
rewind($fp);
$contents = "";
while (!feof($fp)) {
$contents .= fread($fp, 8000);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.