Search code examples
phpphpword

Why does PHPword setvalue not replacing text in word Doc?


I am trying to edit word document using php (PHPword library). However, I am not sure why it is not working. The script did not throw any error.

My Code:

    <?php 
    require 'vendor/autoload.php';
    
    // $phpword = new \PhpOffice\PhpWord\PhpWord();
    $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('test.docx');
    // $templateProcessor->setValues(array('firstname' => 'John', 'lastname' => 'Doe'));
    $templateProcessor->setValue('firstname', 'John');
    $templateProcessor->setValue('lastname', 'Doe');
    
    // var_dump($templateProcessor->setValues(array('firstname' => 'John', 'lastname' => 'Doe')));
    var_dump($templateProcessor->setValue('lastname', 'Doe'))
    ?>

My word Doc: word doc

Output: Output

I have no idea why it is not working. can you please help me ? Thank you


Solution

  • The setValue() method will set the value but not return it to var_dump it.

    Instead you can add:

    $pathToSave = 'path/to/save/file.ext';
    $templateProcessor->saveAs($pathToSave);
    

    and check the output in the generated document.