PHP does not use open source class libraries to export mysql data to Excel files

Source: Internet
Author: User
PHP does not use open source class libraries to export mysql data to Excel files

  1. // Output the excelfile header, which 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. // Obtain data from the database. to save memory usage, do not read data to the memory in one row from the handle.
  6. $ SQL = 'select * from tbl where ...... ';
  7. $ Stmt = $ db-> query ($ SQL );
  8. // Open the php file handle. php: // output indicates that the file is directly output to the browser.
  9. $ Fp = fopen ('php: // output', 'A ');
  10. // Output the Excel column name information
  11. $ Head = array ('name', 'gender ', 'age', 'Email', 'telephony ','...... ');
  12. Foreach ($ head as $ I =>$ v ){
  13. // CSV Excel supports GBK encoding and must be converted; otherwise, garbled characters
  14. $ Head [$ I] = iconv ('utf-8', 'gbk', $ v );
  15. }
  16. // Write data to the file handle through fputcsv
  17. Fputcsv ($ fp, $ head );
  18. // Counter
  19. $ Cnt = 0;
  20. // Refresh the output buffer every $ limit Line. do not set the buffer size to too large or too small.
  21. $ Limit = 100000;
  22. // Extract data row 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 excessive 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. }

It is easy to use, memory saving, and does not rely on third-party class libraries. if you need it, try it on your own.

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.