V
V
Valentine52021-03-23 11:59:46
PHP
Valentine5, 2021-03-23 11:59:46

How to supplement, not overwrite a .docx file?

Greetings!

I used the PHP Word library to create .docx reports from xml files downloaded in a cycle. The $res and $lo variables get a new set of data on each iteration. When I write this data to a Word document in a loop, then each next iteration writes the data over the previously recorded one. And I would need the old information to be saved, and the new one to be added below.. Tell me, please, what am I doing wrong?

My code:

$phpWord = new \PhpOffice\PhpWord\PhpWord();

PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(true);

$section = $phpWord->addSection();

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');

foreach ($tmp as $key => $value) {

    if (is_string($value)) {
        /*var_dump(substr($value, 21));*/
        $cut = $value;
        $output = 'https://yandex.ru/search/xml?user=&key=&query=' . urlencode($cut) . '&lr==ru&sortby=&filter=none&maxpassages=5&groupby=ocs-in-group%3D3';

        $result = file_get_contents($output);

        $al = simplexml_load_string($result);

        $clay = $al->{'response'}->results->grouping->group[0]->doc->title->hlword;
        echo '<pre>';
        print_r($al);
        echo '<pre>';

        foreach ($clay as $sd) {
            $arr[] = '' . $sd . '';
        }
        $res = implode(" ", $arr);

        $arr = [];

        $lo = $al->{'response'}->results->grouping->group[0]->doc->url;

        if($key === 0) {
            $section->addText('Отчет по публикациям информационного агентства');

        }

        $section->addText($res);

        $section->addText($lo);

        $section->addTextBreak();

        $objWriter->save('helloWorld.docx');

    if($key % 3 == 1) {
        $key = $key + 1;
        break;
    }

}

$_SESSION["time"] = $key;

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Adamos, 2021-03-23
@Valentine5

You just need to store the received information, not docx.
From normal information, there is no problem at any time to generate docx - only for output.

A
Alexey Ukolov, 2021-03-23
@alexey-m-ukolov

Source of your problem:

foreach ($tmp as $key => $value) {
  ...

  $objWriter->save('helloWorld.docx');
}

PS Although, I'm not sure about something. Judging by the source code of the library, it should work (albeit with overwriting the file a bunch of extra times).

A
Anton, 2021-03-23
@karminski

If I'm not mistaken, there is no append function in the library. Write the data each time to a new file with a new name.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question