效果
模板
输出模板
代码
下载
composer require phpoffice/phpword
代码案例
include ROOT . "../vendor/autoload.php";
$file = ROOT . 'word/demo.docx';
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($file);
$templateProcessor->cloneBlock('block', 2, true, true);
$var = [
'name#1' => '小明',
'name#2' => '小红'
];
$templateProcessor->setValues($var);
$save_flie = ROOT . 'word/word.docx';
$templateProcessor->saveAs($save_flie);
$open = fopen($save_flie, "rb");
ob_clean();
echo fread($open, filesize($save_flie));
fclose($open);
unlink($save_flie);
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-Type: application/doc");
header("Content-Disposition: attachment; filename=测试.docx");
使用出错解决方式
- 使用docx后缀的word文档,用doc可能导致出错
- 改后缀doc成docx也会报错,需要用wps,office或其他软件转成word
- 链接: 官方文档.