如何使用PHPWord获取Word模板中的占位符/变量列表
如何用PHPWord提取Word模板中的${var_name}格式占位符列表
PHPWord确实没有内置函数直接返回模板中的占位符列表,你可以通过读取模板的XML内容,结合正则匹配来实现这个需求,具体代码示例如下:
use PhpOffice\PhpWord\TemplateProcessor; function getTemplatePlaceholders($templatePath) { // 读取docx模板的核心内容XML $zip = new ZipArchive(); if ($zip->open($templatePath) !== true) { throw new Exception('无法打开目标模板文件'); } $xmlContent = $zip->getFromName('word/document.xml'); $zip->close(); // 正则匹配所有${var_name}格式的占位符 preg_match_all('/\$\{([a-zA-Z0-9_]+)\}/', $xmlContent, $matches); // 去重后返回唯一的占位符列表 return array_unique($matches[1] ?? []); } // 调用示例 $templatePath = 'your-template.docx'; $placeholders = getTemplatePlaceholders($templatePath); print_r($placeholders);
额外说明
- 如果你的占位符包含下划线以外的特殊字符(比如横杠),可以把正则表达式调整为
\$\{([a-zA-Z0-9_-]+)\} - 要是模板里的占位符出现在页眉、页脚,需要额外读取
word/header*.xml和word/footer*.xml文件,把这些内容也加入正则匹配,再合并结果 - 这种方法基于docx的标准压缩包结构,兼容绝大多数常规Word模板
内容的提问来源于stack exchange,提问作者Steen Rabol
相关产品推荐
相关产品推荐

