Laravel Excel - 错误允许的内存大小

Laravel Excel - Error Allowed memory size

我使用 Maatwebsite 加载 excel 个文件。我正在加载好几个文件,直到出现下一个错误:

PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in /project1/vendor/phpoffice/phpexcel/Classes/PHPExcel/Cell.php on line 582

我去 config/excel.php 并将 memoryCacheSize 设置更新为 128MB。之后我 运行 php artisan cache:clearphp artisan config:cache。再次尝试加载,returns 出现同样的错误。

我该如何解决?

将此添加到您的 index.php 文件中。

ini_set('memory_limit', '-1');

您必须增加 PHP 的内存限制。你有很多方法可以做到这一点。

首先,如果你想检查实际内存限制,你需要创建一个 PHP 文件(我们可以将其命名为 php.php)或将其放在任何控制器内的操作中,然后将其中包含以下代码:

<?php phpinfo(); exit;?>

第一种方式修改memory_limit,这种方式修改PHP中所有项目运行的momeoty_limit:

首先你需要找到你的 php.ini,这个数据在 phpinfo();

  1. 编辑 php.ini 。在您的 php.ini 中搜索 "memory_limit" 并更改它的值。如果找不到 "memory_limit",请在 php.ini 末尾添加以下行 memory_limit = 128M ; /* 将 128M 更改为您的需要 */ 保存文件。

  2. 重置 Apache。

    sudo service apache2 restart

第二种选择是将它放在 laravel 项目内的 index.php 中,正如@Giri Annamalai M 在上面告诉你的那样。

ini_set('memory_limit', '-1');

这个选项将修改所有项目的内存限制...如果你输入-1,这意味着没有限制。(取决于计算内存)

其他选项是在controller中指明内存限制,在action中指示内存限制:

ini_set('memory_limit', '-1');

请记住,-1 始终没有限制。也许这不是指示内存限制的最佳安全和性能方式。您还有其他方法可以像 .htaccess 一样编辑内存...但我认为第三个是这个位置最好的之一。

对于较大的文件,我建议使用 box/spout。由于文件类型的灵活性,我都使用过并且通常使用 Maatwebsite 来处理较小的文件。

https://github.com/box/spout

我做了一些调试,看看哪些场景减少了 Laravel Excel 的内存使用。

我最好的结果是使用 DTO,它只包含简单的变量类型。 将 Carbon 或 BigDecimal 等对象转换为字符串也节省了一些内存使用量。

在导出中,您可以删除 withMapping 特征,因为 DTO 属性会为您完成该技巧。如果需要,您可以更改 DTO 属性的顺序。

并删除 ShouldAutoSize 特征,as suggested by the maintainer

例如

class Row {
  public int $id;
  public string $created_at;
}
class UserExport implements FromCollection
{
    public function collection()
    {
        $users = User::query()->all();

        return $users->map(
            function ($user) {
                $row = new Row();
                $row->id = $user->id;
                // cast objects like Carbon or BigDecimal to string
                $row->created_at = $entry->created_at->format('d-m-Y');

                return $row;
            }
        );
    }
}

2021 年 3.1 版将不再有效。

我用 WithChunkReading 得到了它。