V
V
Valentine52020-11-02 18:24:22
PHP
Valentine5, 2020-11-02 18:24:22

PHP: Why does the PHPWORD library throw bugs when writing addText() to a docx file?

Hello!

1) In the browser I get normal XML from the parser.

5fa01e21ccf29926046406.png

2) I'm trying to write data to a Word report (docx file). I use the PHPWord library for this. The code is the following:

$result = file_get_contents($output);
    echo '<pre>';
    var_dump($value);
    var_dump($result);
    echo '</pre>';
    $section->addText($result);
       $objWriter->save('helloWorld.docx');
       sleep(30);


3) Something is written to the file, but MS Word does not open it.

5fa01f550f099852831266.png

4) If I try to open the helloWord.docx file with a notepad, it shows krakozyabry.

5fa0226d8af07952472718.jpeg

5) The first thing that comes to mind is that either the encoding or archiving is something .. but the mystery is that when I tried to write to the same file not the contents of the variable, but just text (I took an example from PHP WORD developer manual):
$section = $phpWord->addSection();
// Adding Text element to the Section having font styled by default...
$section->addText(
    '"Learn from yesterday, live for today, hope for tomorrow. '
        . 'The important thing is not to stop questioning." '
        . '(Albert Einstein)'
);


then he normally signed up to the file. The file opens and shows the text fine. Does this mean that neither encoding nor archiving is to blame for my problem? Then where to look for its solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Valentine5, 2020-11-03
@Valentine5

Figured it out, I had to add PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(true); before all manipulations in the code with Word. It was the XML data itself. Word "didn't understand" some of the special characters in it, as I understand it < and &. the setOutputEscapingEnabled(true) method in PHPWORD is designed to handle unread characters. As a result, I got a normal xml in a Word file. The point is small - to give normal formatting ..

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question