PHP export MySQL data to Excel file

Source: Internet
Author: User

PHP export MySQL data to Excel file reprint


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.



?
1 <br><!--?phpOutput the header of the Excel file, you can change the user.csv to the filename you want (' 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 read the data to memory at once, A row in a clause can be read $sql = ' select * from tbl where ... '; $stmt = $db--->query ($sql); //Open PHP file handle, php://output indicates direct output to browser $f p = 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 through Fputcsv to file handle Fputcsv ($FP, $head); //Counter $cnt = 0;//every $limit line, refresh output buffer, not too big, not too small $limit = 100000; //row-by-line extraction of 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 (); &NBSP;&Nbsp;      $cnt = 0;   }      foreach ($row as $i = > $v) {        $row [$i] = iconv (' utf-8 ', ' GBK ', $v);   } & nbsp;  fputcsv ($fp, $row);}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.