phpword template dynamic block

883 Views Asked by At

I have a word template with this content

${line1}

${line1} template content value from sql is

${block_name} 
${var1}  
${block_name}

Using PhpWord TemplateProcessor, I am able to replace this. In TemplateProcessor.php, I have add

$replace = preg_replace('~\R~u', '</w:t><w:br/><w:t>', $replace);

in function setValue. This is because, the block should be multiline and have no space in order cloneblock to happen.

Then, I save as template2.docx and load again in new TemplateProcessor(). When I open the word file, it already display multiline. But, still cloneblock could not be achieved.

include "db.php";

require_once 'vendor/autoload.php';
use PhpOffice\PhpWord\TemplateProcessor;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;

//1
$templateProcessor = new TemplateProcessor('template.docx');    
//template content value
$templateContentValue=$stmt->fetchAll(PDO::FETCH_ASSOC);
$content        =$templateContentValue[0]['contentVal'];
$templateProcessor->setValue('line', $content);
//save as template2.docx
$pathToSave     ='template2.docx';
$templateProcessor->saveAs($pathToSave);

//2
$templateProcessor2 = new TemplateProcessor($pathToSave);
$replacements = array(
                            array('var1' => 'value1'),
                            array('var1' => 'value2'),
                        );
$templateProcessor2->cloneBlock('block_name', 0, true, false, $replacements);
$templateProcessor2->saveAs('output.docx');

Expected Output:

value1
value2
1

There are 1 best solutions below

0
On

I think maybe you got a typo in the block syntax on last line

By referring to cloneBlock documentation, you are missing a slash(/) in you template content of ${line1}, the content value should be

${block_name} 
${var1}  
${/block_name} // last line of block syntax

In your first word template with content

${line1}

I see your code with

$templateProcessor->setValue('line', $content);

shouldn't it be ?

$templateProcessor->setValue('line1', $content);

So I assume it might just a typo when you're writing the post, which it is not the main issue here.

Another possibility that I can think of after testing using the suggestion from this post with multiline value is, it might due to the unrecognized syntax of newline by PHPWord in your replacement content of ${line1}.

I try with following for frist word template :

${line1}
${line2}
${line3}

Then replace multi values at once

$templateProcessor->setValues([
  'line1' => '${block_name}',
  'line2' => '${var1}',
  'line3' => '${/block_name}'
]);

// same goes to your code starting at line ==> //save as template2.docx

The output is as expected, but I don't think this is what you preferred.

Hope it helps!