Efficient way to export xls,csv in PHP
Often encounter need to export data from the database to Excel file, with some open-source class library, such as Phpexcel, it is quite easy to implement, but the support of a lot of data is not good, it is easy to reach the PHP memory usage limit. The method here is to use the Fputcsv write CSV file method, directly to the browser output Excel file.
GetAll ($sql); Open PHP file Handle, php://output indicates direct output to browser $fp = fopen (' php://output ', ' a '); Output Excel column name information $head = array ("id", "name"), foreach ($head as $i + $v) {//CSV Excel supports GBK encoding, must be converted, otherwise garbled $head [$i] = Iconv (' Utf-8 ', ' GBK ', $v);} Writes data through Fputcsv to the file handle Fputcsv ($FP, $head); Counter $cnt = 0;//every $limit line, refresh the output buffer, not too big, also not too small $limit = 100000; Row-by-line extraction of the data without wasting memory $count = count ($stmt); for ($t =0; $t < $count; $t + +) {$cnt + +); if ($limit = = $cnt) {//Refresh output buffer to prevent problems caused by too much data ob_flush (); Flush (); $cnt = 0; } $row = $stmt [$t]; foreach ($row as $i = + $v) {$row [$i] = iconv (' utf-8 ', ' GBK ', $v); } fputcsv ($fp, $row);}