I'm using PHPExcel library for reading xls and xlsx files. Below is a sample function for demonstrating problem that I have:
public function memoryAction()
{
$filename = "example.xlsx";
echo "<br>Script started<br>";
echo memory_get_usage(true);
$inputFileType = PHPExcel_IOFactory::identify($filename);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadDataOnly(true);
$objReader->setLoadSheetsOnly(array('OTMS','Printing'));
$excelReader = $objReader->load($filename);
echo "<br>Reader Initiliazed<br>";
echo memory_get_usage(true);
foreach ($excelReader->setActiveSheetIndex(0)->getRowIterator() as $row) {
if ($row->getRowIndex() == 1) {
continue;
}
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
$excelRow = array();
foreach ($cellIterator as $cell) {
$columnIndex = $cell->getColumn();
$cellValue = $cell->getCalculatedValue();
$excelRow[$columnIndex] = $cellValue;
}
if (empty($excelRow)) {
continue;
}
echo "<br>Row ".$row->getRowIndex()."<br>";
echo memory_get_usage(true);
}
echo "<br>Went through each row<br>";
echo memory_get_usage(true);
die();
}
So, basically I go through each row in Excel table and output memory usage. The thing is that memory usage increases after each 20-30 rows.
Here are values that I get:
Script started 1835008 -1,75 Mb
Reader Initiliazed 19660800 - 18,75 Mb
Went through each row 47972352 - 45,75 Mb
I read several posts on Internet about PHPExcel memory problem. Yes, it consumes a lot of memory. You can see, that I use setReadDataOnly() function and that I uploaded only specific worksheets. But I still don't understand why just looping through rows consumes memory.
Is there any way to unset row/cell objects in the loop and free up memory? Appreciate any help.
UPD
I have run Mark's code and here is a result for my file:
Base Memory: 1835008
Reader Initialised/File Loaded
19660800
Row 256 memory usage: 24903680
Row 512 memory usage: 33030144
Row 768 memory usage: 38797312
Went through each row
Final memory usage: 48234496
I'm using PHPExcel version 1.7.8. and PHP 5.5.11. Probably it's worth to update PHPExcel library.
UPD 2
I have installed version 1.8.0 of PHPExcel library. Here are results of the Mark's code:
Base Memory: 1835008
Reader Initialised/File Loaded
15990784
Row 256 memory usage: 20185088
Row 512 memory usage: 27262976
Row 768 memory usage: 31719424
Went through each row
Final memory usage: 40108032
Any ideas why it happens? I'm using Zend Framework and called this code in action controller. Test file contains 4 tabs, file size - 619 KB. Code works with first tab only which contains 1000 rows.
$excelRow[$columnIndex] = $cellValue;: are you actually building an array of rows as well? It does raise the question of why you feel the need to build an array in the first place, and secondly why you don't use PHPExcel's built-in methods to do this for you. - Mark Baker