我正在尝试使用从 html 文件检索的文本填充 Word 模板。问题是新创建的 docx 文件中不会创建新行。我得到类似的东西:
<br> - Ingredienti : <br> - 2 Melanzane (circa 1 kg)<br> - 3 spicchi d'aglio<br> - 30 ml di succo di limone<br>
如您所见,
<br>
未翻译为新行。这是我正在使用的代码:
use PhpOffice\PhpWord\TemplateProcessor;
....
function fillTemplate($templatePath, $outputPath, $context) {
try {
// Load the template
$templateProcessor = new TemplateProcessor($templatePath);
PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(true);
// Replace placeholders with provided content
foreach ($context as $placeholder => $content) {
// Replace the placeholder
$templateProcessor->setValue($placeholder, $content);
}
// Save the generated document
$templateProcessor->saveAs($outputPath);
// Output debug information
echo "Template processed successfully. Output saved to: $outputPath\n";
} catch (Exception $e) {
// Handle errors
echo "Error processing template: " . $e->getMessage() . "\n";
}
}
任何帮助/建议表示赞赏
生成的输出 docx 文件显示“
”,而不是在 Word 文档中创建新行。
可能有人需要它,这将解决有关新线路的问题
protected function setValueForPart($search, $replace, $documentPartXML, $limit)
{
// Note: we can't use the same function for both cases here, because of performance considerations.
if (self::MAXIMUM_REPLACEMENTS_DEFAULT === $limit) {
$replace = str_replace("\n", "<w:br/>", $replace);
return str_replace($search, $replace, $documentPartXML);
}
$regExpEscaper = new RegExp();
$replace = str_replace("\n", "<w:br/>", $replace);
return preg_replace($regExpEscaper->escape($search), $replace, $documentPartXML, $limit);
}