skip to Main Content

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

$phpWord = new PhpOfficePhpWordTemplateProcessor(storage_path().'apppublicsamplesample.docx');
$phpWord->setValue('days', '365');
$phpWord->setValue('what', 'Benchmark');
$phpWord->setValue('test', 'KKKK');
$phpWord->setValue('best', 'MMMM');
$phpWord->saveAs(storage_path().'apppublicsamplefinal.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

2

Answers


  1. try to replace the whole title block with a configured title, by using the replaceBlock function. In order to do it, u need to declare a block like this in your word file:

    ${block_name}
    The text you want to replace.
    ${/block_name}
    

    To replace the block with another one implement this line of code into your PHP:

    $phpWord->replaceBlock('block_name', "CIS Microsoft {$days} Foundations {$what}");

    not the cleanest solution but better than nothing. Hope I could help ^^

    Side note:

    your can change multiple values by using:

    $phpWord->setValues(array('test' => 'KKKK', 'best' => 'MMMM'));
    Login or Signup to reply.
  2. 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()."apppublicsamplesample.docx";
    $out = storage_path().'apppublicsamplefinal.docx';
    
    $phpWord = new PhpOfficePhpWordTemplateProcessor($in);
    
    $templateVars = [
      'days'=>'365',
      'what'=>'Benchmark',
      'test'=>'KKKK',
      'best'=> 'MMMM'
    ];
    
    $phpWord->setValues($templateVars);
    
    $phpWord->saveAs($out);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search