Reputation: 521
I am trying to clear an object in phpexcel. Iterating the object several times gives an out of memory error.
The documentation recommends using disconnectWorksheets but it is not working.
Here is the code:
...
$sheet = $instReader->getSheet($sheetOpts['sheet']);
...
echo "memo1:".ys_getmemusage()."\n";
echo "size=". strlen(serialize($instReader))."\n";
$instReader->disconnectWorksheets();
unset($instReader);
unset($sheet);
gc_enable();
gc_collect_cycles();
echo "memo2:".ys_getmemusage()."\n";
exit;
The file is an excel file identified by PHPExcel_IOFactory::identify as Excel2007
The output is:
memo1:memoryused=45.34888458251953 (45meg)
size=5962925
memo2:memoryused=45.34407043457031 (45meg)
anyone know how to solve this problem?
the ys_getmemusage function just gets memory used as below.
$GLOBALS['raymemory_usage'] = memory_get_usage();
function ys_getmemusage() {
$end_memory = memory_get_usage() - $GLOBALS['raymemory_usage'];
$end_memory = $end_memory/(1024*1024);
return "memoryused=$end_memory\n";
}
Upvotes: 1
Views: 2581
Reputation: 316
I was able to fix my memory leak using the accepted answer https://stackoverflow.com/a/27766461/4912853 and a tip from: Dump all variables in PHP:
PHP frees the memory at the end of a function, hence
the_loop()
Before:
foreach($rows as $row){
...
$instReader->disconnectWorksheets();
unset($instReader);
}
After:
function createExcelFile($row){
...
$instReader->__destruct();
unset($instReader);
}
foreach($rows as $row){
createExcelFile($row);
}
The above claim could definitely use a source but these 2 ideas together completely fixed my memory issues after much trial and error. Hope this helps!
Upvotes: 0
Reputation: 521
found the solution
I replaced
$instReader->disconnectWorksheets();
unset($instReader);
with
$instReader->__destruct();
unset($instReader);
and all seems good.
Upvotes: 4