PHP export MySQL data to Excel file

Source: Internet
Author: User
Tags foreach header sql mysql php file stmt
 
 
  1. Output Excel file headers, you can replace user.csv with the file name you want
  2. Header (' Content-type:application/vnd.ms-excel ');
  3. Header (' Content-disposition:attachment;filename= "user.csv");
  4. Header (' cache-control:max-age=0 ');
  5. Get the data from the database, in order to save memory, do not read the data to memory at once, one line in the handle can be read
  6. $sql = ' SELECT * from tbl where ... ';
  7. $stmt = $db->query ($sql);
  8. Open the PHP file handle, php://output for direct output to the browser
  9. $fp = fopen (' php://output ', ' a ');
  10. Output Excel Column name information
  11. $head = Array (' name ', ' gender ', ' age ', ' Email ', ' telephone ', ' ... ');
  12. foreach ($head as $i => $v) {
  13. CSV Excel supports GBK encoding, be sure to convert, otherwise garbled
  14. $head [$i] = iconv (' utf-8 ', ' GBK ', $v);
  15. }
  16. Write data to a file handle by fputcsv
  17. Fputcsv ($fp, $head);
  18. Counter
  19. $cnt = 0;
  20. Every $limit line, refresh the output buffer, not too big, not too small
  21. $limit = 100000;
  22. Fetching data line by row without wasting memory
  23. while ($row = $stmt->fetch (zend_db::fetch_num)) {
  24. $cnt + +;
  25. if ($limit = = $cnt) {//Refresh the output buffer to prevent problems caused by too much data
  26. Ob_flush ();
  27. Flush ();
  28. $cnt = 0;
  29. }
  30. foreach ($row as $i => $v) {
  31. $row [$i] = iconv (' utf-8 ', ' GBK ', $v);
  32. }
  33. Fputcsv ($fp, $row);
  34. }






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.