Jackson
Jackson

Reputation: 1526

Fatal error: Out of memory (allocated 764801024) (tried to allocate 20480 bytes)

I have implemented all things as below

PHP Fatal error: Out of memory (allocated 1707606016) (tried to allocate 426680697 bytes)

Implemented all solutions which mentioned in above post

Still it's giving same error

Fatal error: Out of memory (allocated 764801024) (tried to allocate 20480 bytes)

I also tried setting memory_limit to -1 & even in .htaccess as well.

Using https://www.digitalocean.com/

Below is the code

set_time_limit(0);

error_reporting(E_ALL);
ini_set('display_errors', 1);

$file = file_get_contents("test.csv"); // 50MB File on Server

$data = array_map("str_getcsv", preg_split('/\r*\n+|\r+/', $file));

It gives error on last line. In CSV file have html tags which i'm removing by Code.

Able to upload same file in my Local. Problem is on Sever. How to upload 50MB file on Server?

For now i'm using http://erdconcepts.com/dbtoolbox.html CSVSplitter Which is FREE.

Upvotes: 1

Views: 2543

Answers (1)

stollr
stollr

Reputation: 7183

file_get_contents loads the whole file into memory, which leads to the memory issues.

A better approach is to use a stream. Try to process the CSV file this way:

$fp = fopen('test.csv', 'r');

if ($fp === false) {
    throw new RuntimeException('file not readable');
}

$data = [];

while (!feof($fp)) {
    $row = fgetcsv($fp);
    $data[] = $row;
}

This way fgetcsv reads only one row at a time and not the whole file.

Upvotes: 0

Related Questions