PHPWORD的安装不再赘述,因为网上大部分代码都是将WORD文档保存至服务器上的位置,这样如果用户想下载生成好的文档是不行的,而这里的代码提供用户可以下载生成文档的功能。
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->createSection();
$section->addText('Hello World!');
$file = 'HelloWorld.docx'; //文件名
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$xmlWriter->save("php://output"); //这里不要改
PHPWORD官方文档:https://phpword.readthedocs.io/en/latest/recipes.html#download-the-produced-file-automatically