在PHPWord中操作模板

Joh*_*uel 13 php ms-word phpword

我正在为我正在开发的web-app的报告模块使用PHP文档生成器.我选择PHPWord是因为PHPDocX的免费版本功能非常有限,而且它有一个页脚,它只是一个免费版本.我有一个客户提供的模板.我想要的是我想加载模板并添加动态元素,如附加文本或表格.我的代码在这里:

<?php
require_once '../PHPWord.php';

$PHPWord = new PHPWord();

$document = $PHPWord->loadTemplate('Template.docx');
$document->setValue('Value1', 'Great');

$section = $PHPWord->createSection();
$section->addText('Hello World!');
$section->addTextBreak(2);

$document->setValue('Value2', $section);

$document->save('test.docx');
?>
Run Code Online (Sandbox Code Playgroud)

我尝试创建一个新的部分,并尝试将其分配给模板中的一个变量(Value2),但出现此错误:

[28-Jan-2013 10:36:37 UTC] PHP Warning:  utf8_encode() expects parameter 1 to be string, object given in /Users/admin/localhost/PHPWord_0.6.2_Beta/PHPWord/Template.php on line 99
Run Code Online (Sandbox Code Playgroud)

小智 6

setValue期望第二个参数是一个普通字符串.无法提供节对象.

我已经深入研究了代码,并没有一种简单的方法让一个section对象返回一个可以被setValue函数使用的值.

由于我遇到了同样的问题,我已经为Template.php文件编写了一个补丁,它允许您在使用setValue替换其标记之前克隆表行.每行都有一个唯一的ID,允许您识别每个不同行的模板标记.

这是它的工作原理:

将此函数添加到Template.php文件(在PHPWord目录中找到)

public function cloneRow($search, $numberOfClones) {
    if(substr($search, 0, 2) !== '${' && substr($search, -1) !== '}') {
        $search = '${'.$search.'}';
    }
    $tagPos      = strpos($this->_documentXML, $search);
    $rowStartPos = strrpos($this->_documentXML, "<w:tr", ((strlen($this->_documentXML) - $tagPos) * -1));
    $rowEndPos   = strpos($this->_documentXML, "</w:tr>", $tagPos) + 7;

    $result = substr($this->_documentXML, 0, $rowStartPos);
    $xmlRow = substr($this->_documentXML, $rowStartPos, ($rowEndPos - $rowStartPos));
    for ($i = 1; $i <= $numberOfClones; $i++) {
        $result .= preg_replace('/\$\{(.*?)\}/','\${\\1#'.$i.'}', $xmlRow);
    }
    $result .= substr($this->_documentXML, $rowEndPos);
    $this->_documentXML = $result;
}
Run Code Online (Sandbox Code Playgroud)

在模板文件中,向每个表添加一行,您将用作模板行.假设您已在此行中添加了标记$ {first_name}.

要获得一个包含3行的表,请调用:$ document-> cloneRow('first_name',3);

现在使用包含3行的表更新模板的工作副本.行内的每个标记都附加了#和行号.

要设置值,请使用setValue $ document-> setValue('first_name#1','第一行上的名称'); $ document-> setValue('first_name#2','第二行的名字'); $ document-> setValue('first_name#3','第三行的名字');

我希望这很有用!我将在这里保留代码和文档的更新版本:http://jeroen.is/phpword-templates-with-repeating-rows/