How to make the setValue function work in PHPWord?

1.1k Views Asked by At

I have retrieved the text of a document with PHPWord. Now I would like to modify the data with the setValue function. When I try to do it, it gives me this error:

[05-Jan-2023 17:44:37 UTC] PHP Fatal error:  Uncaught BadMethodCallException: Method setvalue is not defined. in /home/bloggors/translatedocs.bloggors.com/vendor/phpoffice/phpword/src/PhpWord/PhpWord.php:148
Stack trace:
#0 /home/bloggors/translatedocs.bloggors.com/controller/test.php(11): PhpOffice\PhpWord\PhpWord->__call('setvalue', Array)

Here is my code:

<?php

use PhpOffice\PhpWord\Element\AbstractContainer;
use PhpOffice\PhpWord\Element\Text;
use PhpOffice\PhpWord\IOFactory as WordIOFactory;

require_once 'vendor/autoload.php';

$source = 'test/sample-doc-file-for-testing-1.doc';
$objReader = WordIOFactory::createReader('MsDoc');
$phpWord = $objReader->load($source); // instance of \PhpOffice\PhpWord\PhpWord
$phpWord->setValue('Lorem', 'John');

?>

What should I do to solve this problem please?

1

There are 1 best solutions below

0
Afriza On

setValue is a method for TemplateProcessor. You need to use an exisiting .docx file that has variables with the specified search pattern in them.

Let's say you have template.docx:

Lorem ipsum dolor sit amet, ${varName} adipiscing elit.

What setValue does is replace the ${varName} with the value you specify. For example:

$tProcessor = new TemplateProcessor('path/to/template.docx');
$tProcessor->setValue('varName', 'Replacement Text');

So template.docx becomes:

Lorem ipsum dolor sit amet, Replacement Text adipiscing elit.

You can replace the variables with text, charts, etc by using TemplateProcessor. When you're done replacing the variables you can save the edited file to a new file:

$tProcessor->saveAs('path/to/newFile.docx');

By using saveAs, the original template file won't be modified.

By default the search pattern is ${varName}, but you can specify a custom search pattern if you want. Please refer to the documentation: https://phpword.readthedocs.io/en/latest/templates-processing.html

Don't forget to include the TemplateProcessor if you're editor doesn't automatically add it:

use PhpOffice\PhpWord\TemplateProcessor;