PhpWord根据模板生成word文件
未安装phpword时先进行安装
composer require phpoffice/phpword
模板文件只支持.docx类型
use PhpOffice\PhpWord\TemplateProcessor;
$templatePath = 'path/to/your/template.docx';
//创建一个TemplateProcessor实例并加载模版文档
$document = new TemplateProcessor($templatePath);
//模板变量
$data = [
['name'=>'张三','sex'=>'男'],
['name'=>'李四','sex'=>'男'],
['name'=>'小花','sex'=>'女'],
];
//复制某个数据块,每次复制进行不同数据填充(复制多个数据块,单个数据块也可以)
//blockName为数据块名格式如下:
/**
* ${blockName}
* 内容...
* ${/blockName}
*/
//变量名:${name}、${age}
$document->cloneBlock('blockName', 0, true, false, $data);
//保存文档到下面指定文件
$path = 'path/to/your/template/templateNew.docx';
$document->saveAs($path);
//----------------------------
// 设置要替换的变量值,单个模板
// $data = array(
// 'name' => '张三',
// 'age' => 20
// );
//
// // 将变量值应用到模板中
// foreach ($data as $key => $value) {
// $document->setValue($key, $value);
// }
// // 保存为新的Word文件
// $filename = 'path/to/your/template/templateNew.docx';
// $document->saveAs($filename);