PHP implements real-time generation and download of EXCEL files with large data volumes,

Source: Internet
Author: User

PHP implements real-time generation and download of EXCEL files with large data volumes,

Preface

Recently, I received a requirement to export the corresponding user access logs to excel by selecting a time period. Due to the large number of users, I often export 0.5 million pieces of data. The commonly used PHPexcel package requires all the data to be obtained before the excel file can be generated. This obviously causes memory overflow in the face of the excel file that generates a large amount of data, therefore, you need to use PHP to write the output stream while making the Browser Download.

Write the PHP output stream as follows:

$fp = fopen('php://output', 'a');fputs($fp, 'strings');........fclose($fp)

php://outputIs a writable output stream that allows the program to write the output to the output stream like an operation file. PHP will send the content in the output stream to the web server and return it to the browser that initiates the request.

In addition, because excel Data is gradually read from the database and then written to the output stream, you need to set the PHP Execution time to a little longer (30 seconds by default)set_time_limit(0)PHP Execution time is not limited.

Note:The following code illustrates the idea and steps for creating a large data EXCEL file. After removing the project business code, the program may have syntax errors and cannot be run directly. Please fill in the corresponding business code as needed!

/The log file downloaded by * Article access log * is usually large, so first set the Header related to csv, and then open * PHP output stream, incrementally write data to the output stream. After writing data to a certain amount, the system buffer is washed into the response. * avoid buffer overflow */public function articleAccessLog ($ timeStart, $ timeEnd) {set_time_limit (0); $ columns = ['Article id', 'Article title', ......]; $ csvFileName = 'user log '. $ timeStart. '_'. $ timeEnd. '.xlsx'; // indicates that the browser needs to download the headers header ('content-Description: File Transfer ') of the excel File. header ('content-Type: application /Vnd. ms-excel '); header ('content-Disposition: attachment; filename = "'. $ fileName. '"'); header ('expires: 0'); header ('cache-Control: must-revalidate'); header ('pragma: public '); $ fp = fopen ('php: // output', 'A'); // open the output stream mb_convert_variables ('gbk', 'utf-8', $ columns ); fputcsv ($ fp, $ columns); // format the data into CSV format and write it to the output stream $ accessNum = '000000' // obtain the total amount from the database, assume it is 1 million $ perSize = 1000; // The number of items per query $ pages = ceil ($ AccessNum/$ perSize); $ lastId = 0; for ($ I = 1; $ I <= $ pages; $ I ++) {$ accessLog = $ logService-> getArticleAccessLog ($ timeStart, $ timeEnd, $ lastId, $ perSize); foreach ($ accessLog as $ access) {$ rowData = [...... // data of each row]; mb_convert_variables ('gbk', 'utf-8', $ rowData); fputcsv ($ fp, $ rowData ); $ lastId = $ access-> id;} unset ($ accessLog); // release the variable memory // refresh the output buffer to the browser ob_flush (); flush (); // you must use ob_flush () And flush () functions to refresh the output buffer.} Fclose ($ fp); exit ();}

Well, in fact, it is very simple. It is to gradually write the output stream and send it to the browser so that the browser can gradually download the entire file. Because it is gradually written and cannot get the overall size of the file, you cannot set it.header("Content-Length: $size");Before downloading the file, tell the browser how big the file is. But it does not affect the overall effect. The core problem here is to solve the real-time generation and download of large files.

Summary

The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.

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.