使用 PHPWord 的 TemplateProcessor 模板来实现浏览器下载输出,你可以按照以下步骤进行操作:

  1. 首先,确保你已经安装了 PHPWord。你可以通过 Composer 来安装 PHPWord,运行以下命令:
composer require phpoffice/phpword
  1. 创建一个 PHP 文件,并导入 PHPWord 的相关类和命名空间:
<?php
require_once 'vendor/autoload.php';

use PhpOffice\PhpWord\TemplateProcessor;
use PhpOffice\PhpWord\IOFactory;
  1. 创建一个 TemplateProcessor 对象,并加载你的模板文件。假设你的模板文件是 'template.docx':
$templateProcessor = new TemplateProcessor('template.docx');
  1. 根据需要,使用 'setValue' 方法替换模板中的占位符。例如,你可以将 '{name}' 替换为实际的值:
$templateProcessor->setValue('name', 'John Doe');
  1. 保存并输出文件。你可以将文件保存到临时目录中,并使用 'read' 方法读取文件内容,然后向浏览器发送适当的头信息来进行下载:
$tempFile = tempnam(sys_get_temp_dir(), 'phpword');
$templateProcessor->saveAs($tempFile);

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='output.docx'');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($tempFile));
readfile($tempFile);

// 删除临时文件
unlink($tempFile);

这样,当你访问这个 PHP 文件时,浏览器将会下载生成的 Word 文档。

PHPWord TemplateProcessor: 生成并下载 Word 文档

原文地址: https://www.cveoy.top/t/topic/lHzO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录