James Flight
James Flight

Reputation: 1464

Can't find a way to fix PHPExcel memory leak

I am using the following method inside a loop in order to read an excel file in chunks (using a custom read filter so that I don't run out of memory):

public function chunkToArray($file, $startRow, $chunkSize)
{

    $file = __DIR__ . '/../../' . $file;

    $objReader = PHPExcel_IOFactory::createReader('Excel2007');

    $chunkFilter = new ExcelChunkReadFilter();

    $objReader->setReadFilter($chunkFilter);
    $chunkFilter->setRows($startRow, $chunkSize);

    $objPHPExcel = $objReader->load($file);

    $array = $objPHPExcel->getActiveSheet()->rangeToArray('A' . $startRow . ':AT' . ($startRow + $chunkSize - 1));

    $objPHPExcel->disconnectWorksheets();

    unset($objPHPExcel);
    $objPHPExcel = null;

    return $array;
}

Despite calling "disconnectWorksheets" and unsetting and nulling the php excel object, I'm still getting a memory leak on each loop iteration.

I have used echo memory_get_usage(true) to isolate that the memory usage is going up on each iteration on the line $objPHPExcel = $objReader->load($file);, but the memory is not being cleared again before the next iteration.

I'm really struggling to identify what's going on here. Any help greatly appreciated.

Upvotes: 1

Views: 2102

Answers (1)

Aleksandar Rusakov
Aleksandar Rusakov

Reputation: 31

The PHPExcel library has a big problem with memory leaks so I advise you to switch to other libraries that are working with .xlsx files.

Have a look at this answer to the question "Alternative for PHP_excel". You can use PHP_XLSXWriter or Spout.

If you can't switch to another library then you can use the caching mechanism of PHPExcel. This answer can help you with that.

Upvotes: 1

Related Questions