phpphpword

How to change the title of a Word file using PHPWord TemplateProcessor


I am trying to create one .docx file from a template using the below code.

$phpWord = new \PhpOffice\PhpWord\TemplateProcessor(storage_path().'\app\public\sample\sample.docx');
$phpWord->setValue('days', '365');
$phpWord->setValue('what', 'Benchmark');
$phpWord->setValue('test', 'KKKK');
$phpWord->setValue('best', 'MMMM');
$phpWord->saveAs(storage_path().'\app\public\sample\final.docx');

the sample.docs file is like.

enter image description here

but when I run the above code the generated final.docx is like this.

enter image description here

test and best variables are updated but days and what are not updated. days and what are in the title of .docx document. but I am not aware of how to update it using PHPWord

The example sample.doc file link is here


Solution

  • Reformat the document...

    The template you've provided has a "content control" in the title which seems to be incompatible with the library or code. Highlight the title and remove the content control like so: remove the content control

    ..and voila !

    No major changes are required for the code. I have rewritten it for simplicity.

    $in = storage_path()."\app\public\sample\sample.docx";
    $out = storage_path().'\app\public\sample\final.docx';
    
    $phpWord = new \PhpOffice\PhpWord\TemplateProcessor($in);
    
    $templateVars = [
      'days'=>'365',
      'what'=>'Benchmark',
      'test'=>'KKKK',
      'best'=> 'MMMM'
    ];
    
    $phpWord->setValues($templateVars);
    
    $phpWord->saveAs($out);