PhpWord doesn't replace text

pindol picture pindol · May 28, 2013 · Viewed 15k times · Source

I have a docx file and I need to replace some text. This is done inside codeigniter framework; here is the code:

$this->load->library('word');       
$template = $this->word->loadTemplate($_SERVER['DOCUMENT_ROOT'].'/doc/assets/doc3.docx');
$template->setValue('replacename', 'new');
$template->save($_SERVER['DOCUMENT_ROOT'].'/doc/assets/helloWorld.docx');

When I open the new file I still get "replacename" instad of "new". "replacename" is formatted with Verdana font, 9pt font size (no underline or bold). Why it doesn't work? Removing ${ } from setValue function (and from doc file) it works

Answer

Marc picture Marc · Feb 22, 2015

It turns out that when you add text to a word file, it sometimes creates extra tags in the underlying xml file. So (pseudo code) ${NAME} can become <tag1>${</tag1><tag2>NAME</tag2><tag3>}</tag3>

Because of this, phpword can't find your needle.

I'm using a mac with microsoft word and i can just cut all the contents of the word file and paste them again.

Word will than recreate the underlying xml file in which ${NAME} is 1 tag instead of 3.