Posted by examples:

$fileName = './protected/data/template.docx'; $word = new PHPWord(); $word = $word->loadTemplate($fileName); $word->setValue('post', '123'); $h2d_file_uri = tempnam('', 'htd'); $word->save($h2d_file_uri); 

In the document, pasted text and ${post} .
This post is not always replaced with the value I need. And I noticed that if template.docx is opened in WordPad and saved (it will say that some docx data will be lost, because not everything is supported), then post is replaced.

What is the matter, how to be?

    2 answers 2

    I changed the setValue function from the library itself, the problem seems to be solved:

     public function setValue($search, $replace) { if(substr($search, 0, 2) !== '${' && substr($search, -1) !== '}') { //было - $search = '${'.$search.'}'; $search = '/\$\{.*?'.$search.'.*?\}/is'; } if(!is_array($replace)) { //$replace = utf8_encode($replace); } //было - $this->_documentXML = str_replace($search, $replace, $this->_documentXML); $this->_documentXML = preg_replace($search, $replace, $this->_documentXML); } 

      When saving a file in the * .doc format, Word can (not necessarily) replace your ${post} . Better to do everything in two steps:

      1. In Word'e insert in the right places the necessary values ${post}
      2. Save the document to the XML document Word. Open it in a text editor (Notepad ++, PHPStorm), do a search on your ${post} . Most likely, they will be spaced like this:

         <w:r> <w:t> { </w:t> </w:r> <w:r> <w:t> Value1 </w:t> </w:r> <w:r> <w:t> } </w:t> </w:r> 

        You need to transfer everything to one <w:r>${post}</w:r> , it’s better if there are some data in <w:r> : <w:rw:rsidRPr="00BF6D1A"> , and remove the remnants .