public function generateCSV(Model $model, $args = array()) { if (isset($args['dataFormatted'])) { $dataFormatted = $args['dataFormatted']; } else { $dataFormatted = false; } $header = $model->reportsGetHeader($args); $data = $model->reportsGetData($args); //pr($data);die; $fileName = $model->reportsGetFileName($args); $downloadedFile = $fileName . '.csv'; ini_set('max_execution_time', 600); //increase max_execution_time to 10 min if data set is very large $csv_file = fopen('php://output', 'w'); header('Content-type: application/csv'); header('Content-Disposition: attachment; filename="' . $downloadedFile . '"'); $header_row = $header; if (!empty($header_row)) { fputcsv($csv_file, $header_row, ',', '"'); } if ($dataFormatted) { foreach ($data as $row) { fputcsv($csv_file, $row, ',', '"'); } } else { foreach ($data as $arrSingleResult) { $row = array(); foreach ($arrSingleResult as $table => $arrFields) { foreach ($arrFields as $col) { $row[] = $col; } } fputcsv($csv_file, $row, ',', '"'); } } $footer = array(__("Report Generated") . ": " . date("Y-m-d H:i:s")); fputcsv($csv_file, array(), ',', '"'); fputcsv($csv_file, $footer, ',', '"'); fclose($csv_file); }