首页 > 解决方案 > 为什么“deleteBlocks”在 phpWord 中不起作用?

问题描述

我正在尝试在我的 Word 文档中使用块,但我遇到了一些问题。首先,当我在文档中声明一个块时,如果我不使用函数“cloneBlock”,结果如下所示:

${sec}
example
${/sec}

也许我必须使用该功能才能正常显示。但我的主要问题是“deleteBlock”不起作用。如果我不克隆块,则生成的 docx 已损坏。但是,如果我克隆该块,“deleteBlock”函数不会删除该块,它会在我的最终 docx 文件中显示该块内的信息。

这是我的代码:

//Word
// Creating the new document...
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('../example.docx');
//set value
//$templateProcessor->setValue('title', 'Example');

//Triplicate block
$templateProcessor->cloneBlock('firstblock', 3, true, true);
$templateProcessor->setValue('firstname#1', 'John');
$templateProcessor->setValue('lastname#1', 'Doe');
$templateProcessor->setValue('firstname#2', 'John');
$templateProcessor->setValue('lastname#2', 'Doe');
$templateProcessor->setValue('firstname#3', 'John');
$templateProcessor->setValue('lastname#3', 'Doe');

//Delete Block
$templateProcessor->cloneBlock('sec', 1, true, true);
$templateProcessor->deleteBlock('sec');
$templateProcessor->saveAs('example.docx');

Docx模板:

${firstblock}
Hello ${firstname} ${lastname}!
${/firstblock}
${sec}
example
${/sec}

更新:我没有使用函数“deleteBlock”,而是使用了这样的函数“cloneBlock”,它删除了块:

//Delete Block
$templateProcessor->cloneBlock('sec', 0, true, true);

所以,我已经写了0次克隆块,所以它消失了但是我还有另一个问题。我不知道为什么,但这只是有时有效

标签: blockphpword

解决方案


我不确定为什么用户 @d1845412 删除了他们之前的答案,但它实际上解决了我的问题。我用以下代码覆盖了 deleteBlock 方法,它似乎可以工作。比起对 replaceBlock 方法的较大更改,我更喜欢这种小改动。

/**
 * Override this method since deleteBlock doesn't seem to work.
 * @param string $blockname
 */
public function deleteBlock($blockname)
{
    $this->cloneBlock($blockname, 0, true, true);
}

推荐阅读