I have a PHP script running using YII framework that goes through the database and creates and Excel sheet for export purposes. The data in the database is around 15K records now and increasing. The issue is that the script consumes a lot of memory and the excel file generated becomes around 45 MB. I can try to zip the file to compress it to the size which i dont think would be an issue but the script using more memory is my concern.
One way I was thinking of solving it was to process only 5k records at one time and then add all of them up to create the Excel file. I am not sure if this would be that way to go.
public function actionExport() {
Yii::import('ext.phpexcel.XPHPExcel');
XPHPExcel::init();
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Adding data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'SN')
->setCellValue('B1', 'Full Name')
->setCellValue('C1', 'Gender')
->setCellValue('D1', 'Date Of Birth')
->setCellValue('E1', 'Products')
$merchantModels = Merchant::model()->findAll();
$i = 2; //starting after the header row
foreach ($merchantModels as $model) {
$merchantPModels = MerchantProducts::model()->findAll(array(
'condition' => 'merchantID = :merchantID',
'params' => array(':merchantID' => $model->id),
));
$productStr= "";
$pStr ="";
$x = 0; // counter for the merchnat product Loop
foreach ($merchantModels as $MPmodel) {
if($MPmodel->product !== null){
$pStr = $MPmodel->product->productName;
}else{
$pStr = "";
}
if ($x == 0) { // First Object
$productStr = $pStr;
}else{
$productStr = $productStr . "," . $pStr;
}
$x++;
}
*
*/
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A' . $i, $i - 1)
->setCellValue('B' . $i, $model->fullName)
->setCellValue('C' . $i, $model->gender)
->setCellValue('D' . $i, $model->dateOfBirth)
->setCellValue('E' . $i, $productStr);
$i++;
}
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Merchants');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
$date = new DateTime('NOW');
$date = $date->format('Y-m-d H:i:s'); // for example
$this->render('export', array(
'excelModel' => $objPHPExcel,
'date' => $date,
));
}