Recently I am working on a backend management project, and there is usually a need to export data to excel in the backend. After previous searches, it is usually recommended to use php excel. I often use laravel, and there is also a very useful corresponding package for php excel.
It is very easy to use at first, but when the data that needs to be exported reaches tens of thousands, it will directly cause the problem of insufficient memory.
Then I found several solutions.
Front-end solution
PHP cooperates with SheetJS/js-xlsx to export a large amount of Excel data
The benefits of this solution are not required Additional interfaces, but dependent on front-end developers.
Export to csv
This solution is faster and fully back-end implemented. The disadvantage is that the csv format has relatively high requirements on the export form, and the requirement is pure Data cannot exist in rich text form such as pictures.
The following mainly introduces how to export csv
Introduction to php official documentation
<?php $list = array ( array('aaa', 'bbb', 'ccc', 'dddd'), array('123', '456', '789'), array('"aaa"', '"bbb"') ); $fp = fopen('file.csv', 'w'); foreach ($list as $fields) { fputcsv($fp, $fields); } fclose($fp); ?>
Export complete example
<?php $name = 'test'; header ( "Content-type:application/vnd.ms-excel" ); header ( "Content-Disposition:filename=".$name.".csv" ); header ('Cache-Control: max-age=0'); //打开PHP文件句柄,php://output 表示直接输出到浏览器 $fp = fopen('php://output', 'a'); // 写入BOM头,防止乱码 fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF)); // 生成的测试数据 function test() { for ($i=0; $i < 150000; $i++) { yield ['name', $i, '男']; } } // 表头 $headers = ['名字', '年龄', '性别']; fputcsv($fp, $headers); foreach (test() as $value) { fputcsv($fp, $value); } fclose($fp); ?>
Using it with chunk in laravel can easily and quickly export all data.
Related recommendations:
Sharing tips on how to export data to excel using Python
Speculative: How to use PHP to export data Export to Excel table (graphic explanation)
php exports data to execl file format
The above is the detailed content of Detailed explanation of PHP data export knowledge points. For more information, please follow other related articles on the PHP Chinese website!