使用PhpWord生成ms word文档

Generate ms word document using PhpWord

我将使用 PhpWord 生成一些文档,我有一些草稿文档,我在其中动态设置 client_name

$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($draftUrl);
$templateProcessor->setValue("client_name", $clientName);

$filename = '30.docx';
$templateProcessor->saveAs($filename);

然后我读取了这个文件,用户可以下载它

header('Content-Type: application/octet-stream');
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-Disposition: attachment; filename='$filename'");
readfile($filename);

当我尝试通过 MsOffice 打开它时,我收到以下消息:

当我点击 OK 时:

在接受这个之后,我终于看到我的文件准备好了。我需要什么来生成可读文档?

我刚刚在阅读之前将 ob_clean() 添加到我的代码中,一切正常。

This function discards the contents of the output buffer.

This function does not destroy the output buffer like ob_end_clean() does.

所以我确保不需要的输出不会进入生成的文档。

$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($draftUrl);
$templateProcessor->setValue("client_name", $clientName);

$filename = '30.docx';
$templateProcessor->saveAs($filename);

header('Content-Type: application/octet-stream');
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-Disposition: attachment; filename='$filename'");
ob_clean();
readfile($filename);