Laravel PhpWord 强制下载无错误

Laravel PhpWord force download whithout error

我使用 Laravel 5.3 和 phpWord 0.14

我创建我的 word 文档。

$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$section->addText( 'Ikerkuntza taldea' , array('name' => 'Tahoma', 'size' => 13, 'bold' => true) );
$phpWord->save('GIE.docx');

它工作并在 public/ 文件夹

中创建了 GIE.docx

但是...我想强制下载

我找到了 2 种不同的形式来执行此操作,但是当我从我的计算机打开 word 文件时,两者都给我错误。

$phpWord->save('GIE.docx', 'Word2007', true);

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('GIE.docx');

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
header("Content-Disposition: attachment; filename='GIE.docx'");
$objWriter->save("php://output");

都给我报错文件损坏

我找到了解决方案。

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save("GIE.docx");
header('Pragma: no-cache');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment; filename=GIE.docx;');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize('GIE.docx'));
readfile('GIE.docx');
unlink('GIE.docx');