Reputation: 372
Is it possible to just do a simple find and replace for text on a Word document using PHPWord? From what I've seen, the closest you can get is just ADDING text to a section, and you can't manipulate existing text except for font, etc. If not, is there anything free that I can use to do this?
Upvotes: 20
Views: 18214
Reputation: 131
Install
composer require phpoffice/phpword
PHP code
include 'vendor/autoload.php';
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('test2.docx');
$templateProcessor->setValue('name', 'myvar');
$templateProcessor->saveAs('./xx.docx');
My test.docx just has the word: ${name}
Upvotes: 13
Reputation: 1149
You can use setValue in order to achieve what you are looking for. Take a look at the samples.
Here is the method: https://github.com/PHPOffice/PHPWord/blob/e35838f7d7928b2308df3f7f0ef6d49bf96f453c/src/PhpWord/Template.php#L131
Upvotes: 7
Reputation: 8331
No, PHPWord is only intented to create docx files.
Anyhow, a docx file is simply a collection of xml files in a zip container. In general what you need to do is:
Beware that Word has a tendency to split words in multiple sections, depending on what was done with the document at save point. There may be Bookmarks, language changes, spellchecking or character formating tags in the middle of any word.
Good luck to find a safe way to handle this.
Upvotes: 7