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?
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:
What setValue does is replace the ${varName} with the value you specify. For example:
So template.docx becomes:
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:
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: