-
- // Output the 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 data from the database. In order to save memory, do not put the data Read the memory at one time and read it line by line from the handle
- $sql = 'select * from tbl where ...';
- $stmt = $db->query($sql);
-
- // Open the PHP file Handle, php://output means output directly to the browser
- $fp = fopen('php://output', 'a');
-
- // Output Excel column name information
- $head = array('name' , 'Gender', 'Age', 'Email', 'Telephone', '...');
- foreach ($head as $i => $v) {
- // Excel for CSV supports GBK encoding, must be Convert, otherwise garbled characters
- $head[$i] = iconv('utf-8', 'gbk', $v);
- }
-
- // Write the data to the file handle through fputcsv
- fputcsv($fp, $head );
-
- //Counter
- $cnt = 0;
- // Every $limit line, refresh the output buffer, not too big, not too small
- $limit = 100000;
-
- // Take out the data line by line, Don’t waste memory
- while ($row = $stmt->fetch(Zend_Db::FETCH_NUM)) {
-
- $cnt ++;
- if ($limit == $cnt) { //Refresh the output buffer to prevent Too much data causes problems
- ob_flush();
- flush();
- $cnt = 0;
- }
-
- foreach ($row as $i => $v) {
- $row[$i] = iconv(' utf-8', 'gbk', $v);
- }
- fputcsv($fp, $row);
- }
Copy code
Easy to use, saves memory, and does not rely on third-party libraries , friends in need, please try it yourself.
|