【发布时间】:2020-12-24 15:12:57
【问题描述】:
我有什么:
- 模板文档
template.docx内部带有标记 -${position_to_insert_text} - 变量
$text_to_insert_in_template中的字符串,内部带有<strong>html标签-My <strong>example string</strong> with html tag.
我想要什么:
- 打开模板
template.docx - 将
${position_to_insert_text}替换为$text_to_insert_in_template - 在
<strong>和</strong>标记之间插入的文本必须采用强格式 - 我的示例字符串 带有 html 标记。
我的工作:
$text_to_insert_in_template = 'My <strong>example string</strong> with html tag.';
$template_path = 'templates/template.docx';
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($template_path);
$templateProcessor->setValue('position_to_insert_text', $text_to_insert_in_template);
$templateProcessor->saveAs('result.docx');
结果:
损坏的result.docx 文档无法打开它。原因 - 未处理 html 标签。如果htmlspecialchars($text_to_insert_in_template) 结果我可以打开result.docx 但html标签显示为纯文本。
我尝试将 html 标签替换为原生单词标签
$text_to_insert_in_template = 'My <strong>example string</strong> with html tag.';
$template_path = 'templates/template.docx';
$text_to_insert_in_template = str_replace('<strong>', "<w:b val='true'/>", $text_to_insert_in_template);
$text_to_insert_in_template = str_replace('</strong>', "<w:b val='false'/>", $text_to_insert_in_template);
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($template_path);
$templateProcessor->setValue('position_to_insert_text', $text_to_insert_in_template);
$templateProcessor->saveAs('result.docx');
结果我可以打开result.docx,但里面的文本也没有格式和html标签:
我怎样才能得到我想要的结果? - 我的 示例字符串 带有 html 标记。
【问题讨论】: