Search code examples
laravelout-of-memoryphp-ziparchivephpword

Allowed memory size problem in phpword/src/PhpWord/Shared/ZipArchive.php


I tried to use TemplateProcessor (phpword in laravel 7) to create a docx from a defined template but i got this error :

FastCGI sent in stderr: "PHP message: PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 262144 bytes) in ****/vendor/phpoffice/phpword/src/PhpWord/Shared/ZipArchive.php on line 131 PHP message: PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 262144 bytes) in Unknown on line 0"

When i set ini_set('memory_limit', '-1'); or rise the memory limit in my php.ini, i got : Maximum execution time of 30 seconds exceeded I can rise the maximum execution time but still got the same error. The function that responsable for this error is :

public function open($filename, $flags = null)
{
    $result = true;
    $this->filename = $filename;
    $this->tempDir = Settings::getTempDir(); // the 131 line who responsable for the error 

    if (!$this->usePclzip) {
        $zip = new ZipArchive();
        $result = $zip->open($this->filename, $flags);

        // Scrutizer will report the property numFiles does not exist
        // See https://github.com/scrutinizer-ci/php-analyzer/issues/190
        $this->numFiles = $zip->numFiles;
    } else {
        $zip = new \PclZip($this->filename);
        $zipContent = $zip->listContent();
        $this->numFiles = is_array($zipContent) ? count($zipContent) : 0;
    }
    $this->zip = $zip;

    return $result;
}

php -v

    PHP 7.4.7 (cli) (built: Jun 12 2020 07:48:26) ( NTS )

I searched everywhere but i didn't found anything to solve this problem. Thanks in advance


Solution

  • I found a solution for this problem by remplacing zipArchive with pclzip in the setting of phpword :

    Path to setting : .../vendor/phpoffice/phpword/src/PhpWord/Settings.php
    

    Change this :

        private static $zipClass = self::ZIPARCHIVE;
    

    By this :

        private static $zipClass = self::PCLZIP;
    

    I tested this for the 0.16.0 and 0.17.0 versions and it works like magic :)

    PS : Maybe you have to install the pclzip to turn this on. Pclzip installation