


PHP generates and downloads EXCEL files with extremely large amounts of data in real time
Recently received a request to export the corresponding user access logs to excel through the selected time period. Due to the large number of users, it is often the case that more than 500,000 data are exported.
The commonly used PHPexcel package needs to get all the data before it can generate excel. This will obviously cause memory overflow when faced with generating an excel file with a large amount of data, so consider using PHP to write at the same time. The output stream allows the browser to complete the request in the form of download.
We write the PHP output stream in the following way
$fp = fopen('php://output', 'a'); fputs($fp, 'strings'); .... .... fclose($fp)
php://output is a writable output stream, allowing the program to write output to the output stream like a file. , PHP will send the content in the output stream to the web server and return it to the browser that initiated the request
In addition, since the excel data is gradually read from the database and then written to the output stream, the execution of PHP needs to be Set the time longer (default 30 seconds) set_time_limit(0) does not limit PHP execution time.
Note:
The following code only illustrates the ideas and steps for generating EXCEL with large amounts of data. After removing the project business code, the program has syntax errors and cannot be run directly. , please fill in the corresponding business code according to your own needs!
/** * 文章访问日志 * 下载的日志文件通常很大, 所以先设置csv相关的Header头, 然后打开 * PHP output流, 渐进式的往output流中写入数据, 写到一定量后将系统缓冲冲刷到响应中 * 避免缓冲溢出 */ public function articleAccessLog($timeStart, $timeEnd) { set_time_limit(0); $columns = [ '文章ID', '文章标题', ...... ]; $csvFileName = '用户日志' . $timeStart .'_'. $timeEnd . '.xlsx'; //设置好告诉浏览器要下载excel文件的headers header('Content-Description: File Transfer'); 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');//打开output流 mb_convert_variables('GBK', 'UTF-8', $columns); fputcsv($fp, $columns);//将数据格式化为CSV格式并写入到output流中 $accessNum = '1000000'//从数据库获取总量,假设是一百万 $perSize = 1000;//每次查询的条数 $pages = ceil($accessNum / $perSize); $lastId = 0; for($i = 1; $i <= $pages; $i++) { $accessLog = $logService->getArticleAccessLog($timeStart, $timeEnd, $lastId, $perSize); foreach($accessLog as $access) { $rowData = [ ......//每一行的数据 ]; mb_convert_variables('GBK', 'UTF-8', $rowData); fputcsv($fp, $rowData); $lastId = $access->id; } unset($accessLog);//释放变量的内存 //刷新输出缓冲到浏览器 ob_flush(); flush();//必须同时使用 ob_flush() 和flush() 函数来刷新输出缓冲。 } fclose($fp); exit(); }
Okay, it’s actually very simple. It is to write the output stream step by step and send it to the browser to let the browser download the entire file step by step. Since it is written step by step, the overall size of the file cannot be obtained, so there is no The method is to tell the browser how big the file is before downloading by setting header("Content-Length: $size");. However, it does not affect the overall effect. The core problem here is to solve the real-time generation and download of large files.
Update: Let me talk about my idea of database query here, because the data gradually written to EXCEL actually comes from the paging query of Mysql. Everyone knows that the syntax is LIMIT offset, num, but as The larger the offset, the more rows MySQL needs to skip in each paging query, which will seriously affect the efficiency of MySQL queries (including NoSQL such as MongoDB, it is not recommended to skip multiple rows to get the result set), so I use LastId to do paging queries.
Similar to the following statement:
SELECT columns FROM `table_name` WHERE `created_at` >= 'time range start' AND `created_at` <= 'time range end' AND `id` < LastId ORDER BY `id` DESC LIMIT num
The above is the detailed content of PHP generates and downloads EXCEL files with extremely large amounts of data in real time. For more information, please follow other related articles on the PHP Chinese website!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6
Visual web development tools