Quantcast
Channel: PHPWord
Viewing all articles
Browse latest Browse all 450

Created Unassigned: Template::setValue() shortcomings [66]

$
0
0
The Template::setValue() method seems to have a couple of issues that I've discovered.

Firstly, as documented, "only single-line values can be replaced". I have found that it is possible to insert multiline values using the <w:br/> tag. The function could probably be modified as follows to achieve this:

```
public function setValue($search, $replace) {
if(substr($search, 0, 2) !== '${' && substr($search, -1) !== '}') {
$search = '${'.$search.'}';
}

if(!is_array($replace)) {
$replace = utf8_encode($replace);
$replace = str_replace("\n", "<w:br/>", $replace);
}

$this->_documentXML = str_replace($search, $replace, $this->_documentXML);
}
```

Note that I haven't given any thought to character sets or any other validation, but in principal that should work.

The second issue I found is that often setValue() simply doesn't work at all. I found forum threads where other people have had this issue, but the ones I read didn't manage to figure out what the issue was.

I took a look at the word/document.xml file in my docx file and found somewhat of a mess. Word inserts lots of additional markup as a document is being edited. There are hooks for the spelling and grammar checker that tell it where to put the red and green zig-zag underlines. In addition, if you modify existing text you often get additional <w:r>, <w:t> and various other tags thrown in.

You might have added a place holder like:

```
${placeHolder1}
```

but what's actually in word/document.xml is:

```
<w:r><w:t>${</w:t></w:r><w:proofErr w:type="gramStart"/><w:r><w:t>placeHolder1</w:t></w:r><w:proofErr w:type="gramEnd"/><w:r><w:t>}</w:t></w:r>
```

setValue() uses only a very simplistic str_replace() function which has no understanding of the format of the XML document and is completely unequipped to handle this.

Ideally, I believe that the setValue() function needs to be rewritten using DOM methods so that it can handle the extra chaff that Word inserts.

In the meantime, I found that switching of spelling and grammar checking in Word's preferences removed the <w:proofErr> tags and after that manually deleting and completely retyping any placeholders that need to be changed (rather than modifying existing placeholder text) gets rid of the <w:r> and <w:t> tags. I was very carful to check the word/document.xml file afterwards!

Viewing all articles
Browse latest Browse all 450

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>