- Output Excel file header, you can replace user.csv with the file name you want
- Header (' Content-type:application/vnd.ms-excel ');
- Header (' content-disposition:attachment;filename= ' user.csv "');
- Header (' cache-control:max-age=0 ');
- Get the data from the database, in order to save memory, do not read the data once to the memory, the subordinate handle in a row to read
- $sql = ' SELECT * from tbl where ... ';
- $stmt = $db->query ($sql);
- Open PHP file handle, php://output direct output to 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 support GBK encoding, be sure to convert otherwise garbled
- $head [$i] = iconv (' utf-8 ', ' GBK ', $v);
- }
- Writes data to a file handle via Fputcsv
- Fputcsv ($fp, $head);
- Counter
- $cnt = 0;
- Every $limit line, refresh the output buffer, not too big, not too small
- $limit = 100000;
- Row-by-line data extraction without wasting memory
- while ($row = $stmt->fetch (zend_db::fetch_num)) {
- $cnt + +;
- if ($limit = = $cnt) {//Refresh output buffer to prevent problems caused by excessive data
- Ob_flush ();
- Flush ();
- $cnt = 0;
- }
- foreach ($row as $i = = $v) {
- $row [$i] = iconv (' utf-8 ', ' GBK ', $v);
- }
- Fputcsv ($fp, $row);
- }
Copy CodeEasy to use, but also save memory, and do not rely on the third-party class library, the need for friends to try it out on their own. |