出现这个错误消息,有什么建议吗?

允许内存大小为33554432字节已耗尽(已尝试分配 43148176字节)的PHP


当前回答

如果您的脚本需要分配这么大的内存,那么您可以通过在php文件中添加这一行来增加内存限制

ini_set('memory_limit', '44M');

其中,4400万是你预计消费的数量。

但是,大多数情况下,此错误消息意味着脚本正在做错误的事情,增加内存限制只会导致相同的错误消息,但数字不同。

因此,您必须重写代码,而不是增加内存限制,这样它就不会分配那么多内存。例如,在较小的块中处理大量数据,取消保存大值但不再需要的变量,等等。

其他回答

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

如果您的脚本需要分配这么大的内存,那么您可以通过在php文件中添加这一行来增加内存限制

ini_set('memory_limit', '44M');

其中,4400万是你预计消费的数量。

但是,大多数情况下,此错误消息意味着脚本正在做错误的事情,增加内存限制只会导致相同的错误消息,但数字不同。

因此,您必须重写代码,而不是增加内存限制,这样它就不会分配那么多内存。例如,在较小的块中处理大量数据,取消保存大值但不再需要的变量,等等。

It is unfortunately easy to program in PHP in a way that consumes memory faster than you realise. Copying strings, arrays and objects instead of using references will do it, though PHP 5 is supposed to do this more automatically than in PHP 4. But dealing with your data set in entirety over several steps is also wasteful compared to processing the smallest logical unit at a time. The classic example is working with large resultsets from a database: most programmers fetch the entire resultset into an array and then loop over it one or more times with foreach(). It is much more memory efficient to use a while() loop to fetch and process one row at a time. The same thing applies to processing a file.

我有同样的问题,在命令行运行php。最近,我更改了php.ini文件,在更改php.ini时犯了一个错误

这是针对php7.0的

到php.ini的路径:/etc/php/7.0/cli/php.ini

我设置了memory_limit = 256(这意味着256字节),而不是memory_limit = 256M(这意味着256兆字节)。

; 脚本可能消耗的最大内存(128MB) ; http://php.net/memory-limit memory_limit = 128M

一旦我纠正了它,我的过程开始正常运行。

如果您试图读取一个文件,这将占用PHP中的内存。例如,如果您试图打开并读取一个MP3文件(例如,$data = file("http://mydomain.com/path/sample.mp3")),它将把它全部拉到内存中。

正如Nelson所建议的,如果您确实需要使用这么多内存,您可以提高您的最大内存限制。