替换 Word 模板

文档

文档:https://phpoffice.github.io/PHPWord/
github:https://github.com/PHPOffice/PHPWord

安装

composer require phpoffice/phpword

使用

use zxf\Office\Word\Template;

// 模板文件,里面需要替换的内容变量使用${}括起来,例如${name}、${by_author}
$docPath = '/Users/linian/Desktop/document.docx';

// 创建 Template 类的实例
$template = new Template($docPath);

// 替换的内容字段在模板中是使用${}括起来的,在调用替换时${}是可以省略的,eg: ${name}、name 、${by_author}、by_author都是等效的
$template->replaceText([
    '${name}'    => '张三',
    '${content}' => '欢迎光临',
    'by_author'  => '威四方',
]);

// 模板中的图片变量${logo},在替换时使用${logo}或logo都可以
$template->replaceImage('logo', [
    'path'   => '/Users/linian/Pictures/1.jpeg',
    'width'  => 100, // 设置图片宽度
    'height' => 100, // 设置图片高度
    'ratio'  => true,  // 保持图片比例
]);

// 方式一:保存
$template->save('/path/example_download.docx');

// 方式二:直接下载文档
$template->download('example_download.docx');

// 方式三:保存并下载文档
$template->saveAndDownload('/Users/linian/Desktop/document_download.docx');