Search code examples
phpcharacterfile-conversionphpword

How to make characters safer for PHPWord


I am running the following conversion with the PHPWord library:

$section = $document->addSection();
$output = mb_substr(strip_tags($page['content'][0]['settings']['text']),0,1760);
$section->addText($output);

Using 1760 characters gives me nice output in a word document, while using 1761 characters gives me a blank page. The extra character is an ampersand -- the first use of that character in my string.

Other than playing whack-a-more by calling str_replace for every character found to be problematic, is there a simple way to make this character safe for PHPWord?


Solution

  • you can use the htmlspecialchars function for that (something that is used consistently in all the library examples as well):

    $section = $document->addSection();
    $output = htmlspecialchars(strip_tags($page['content'][0]['settings']['text']), ENT_COMPAT, 'UTF-8');
    $section->addText($output);