PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 10, 2022

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

 November 10, 2022     php, phpword     No comments   

Issue

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);


Answered By - Drk
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing