我正在使用 phpword 模板处理器来替换 word 模板中的变量并另存为新文档。然后,我加载输出文档并使用 xsl 更改段落中的文本。为了检索特定段落节点以更改文本,我在替换变量之前使用 xsl 将自定义属性
w:id
添加到变量 w:p。然后,我使用 xsl 使用添加的属性更改段落中的文本。但是,价值保持不变。它应该从value1
变为new Value1
.
setAttribute.xsl
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
exclude-result-prefixes="w">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match='w:p[w:r/w:t="${para1}"]'>
<xsl:copy>
<xsl:attribute name="w:id">1</xsl:attribute>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
SetAttributeSetValue.php
<?php
include_once 'vendor/autoload.php';
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('3-template.docx');
//add attribute with value to paragraph
$xslDomDocument = new \DOMDocument();
$xslDomDocument->load('setAttribute.xsl');
$templateProcessor->applyXslStyleSheet($xslDomDocument);
$para1val='value1';
$templateProcessor->setValue('para1',$para1val);
$templateProcessor->saveAs('output.docx');
更新段落值.xsl
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
exclude-result-prefixes="w"
>
<xsl:param name="replacement" select="'new Value1'"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match='w:p[@w:id="1"]/w:r/w:t/text()'>
<xsl:value-of select="$replacement" />
</xsl:template>
</xsl:stylesheet>
updateParagraphValue.php
<?php
include_once 'vendor/autoload.php';
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('output.docx');
$xslDomDocument = new \DOMDocument();
$xslDomDocument->load('updateParagraphValue.xsl');
$templateProcessor->applyXslStyleSheet($xslDomDocument);
$templateProcessor->saveAs('output2.docx');