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.
//output Excel file header, you can change user.csv to the file name you want (' Content-type:application/vnd.ms-excel '); Header (' Content-disposition:attachment;filename= "User.csv"); Header (' cache-control:max-age=0 '); To get the data from the database, in order to save memory, do not read the data to memory at once, a row of the clause can be read $sql = ' select * from tbl where ... '; $stmt = $db->query ($sql); Open the PHP file handle, php://output indicates the direct output to the browser $fp = fopen (' php://output ', ' a '); Output Excel column name information $head = Array (' name ', ' gender ', ' age ', ' Email ', ' phone ', ' ... '); foreach ($head as $i = + $v) {//CSV Excel supports GBK encoding, be sure to convert otherwise garbled $head [$i] = iconv (' utf-8 ', ' GBK ', $v);}//Data passing through F Putcsv write to file handle Fputcsv ($FP, $head); Counter $cnt = 0; Every $limit line, refresh the output buffer, not too big, not too small $limit = 100000; Row-by-line extraction of the data without wasting memory while ($row = $stmt->fetch (zend_db::fetch_num)) {$cnt + +; if ($limit = = $cnt) {//Refresh output buffer to prevent problems caused by too much data ob_flush (); Flush (); $cnt = 0; } foreach ($row as $i = + $v) {$row [$i] = iconv (' utf-8 ', ' GBK ', $v); } fputcsv ($fp, $row); }
Easy to use, very memory-saving, no reliance on third-party class libraries.
http://www.bkjia.com/PHPjc/752360.html www.bkjia.com true http://www.bkjia.com/PHPjc/752360.html techarticle 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, very easy ...