Efficient php export of xls, csv methods often encounter the need to export data from the database to Excel files, using some open source class libraries, such as PHPExcel, is indeed easier to implement, however, the support for a large amount of data is very poor, and it is easy to reach the PHP memory usage limit. The method here is to use fputcsv to write a CSV file and directly output an Excel file to the browser. & Lt ;? Php efficient php export of xls and csv methods
I often encounter the need to export data from a database to an Excel file. using some open-source class libraries, such as PHPExcel, is indeed easy to implement, but it does not support a lot of data, it is easy to reach the PHP memory usage limit. The method here is to use fputcsv to write a CSV file and directly output an Excel file to the browser.
GetAll ($ SQL); // open the php file handle. php: // output indicates that the file is directly output to the 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 and must be converted. otherwise, garbled code $ head [$ I] = iconv ('utf-8', 'gbk', $ v );} // write data to the file handle fputcsv ($ fp, $ head) through fputcsv; // counter $ cnt = 0; // refresh the output buffer every $ limit row, do not be too large or too small $ limit = 100000; // Extract data row by row without wasting memory $ count = count ($ stmt); for ($ t = 0; $ t <$ count; $ t ++) {$ cnt ++; if ($ limit = $ cnt) {// refresh the output buffer, prevent problems caused by excessive data: ob_flush (); flush (); $ cnt = 0 ;}$ row = $ stmt [$ t]; foreach ($ row as $ I =>$ v) {$ row [$ I] = iconv ('utf-8', 'gbk', $ v );} fputcsv ($ fp, $ row );}