Analysis of knowledge points derived from PHP data

  • 2021-09-11 19:43:13
  • OfStack

Recently, I am doing the project of background management, and the background usually needs to export data to excel. After previous search, it is usually recommended to use php excel, I often use laravel, and there is also a good corresponding package for php excel.

It is very useful to start using it, but when tens of thousands of pieces of data need to be exported, it will directly bring about the problem of insufficient memory.

Then I found several solutions.

Front-end solution

PHP cooperates with SheetJS/js-xlsx to derive a large amount of Excel data

The benefits of this solution do not require additional interfaces, but depend on the front-end developers.

Export to csv

The scheme is fast, complete back-end implementation, the disadvantage is that csv format for the export form requirements are relatively high, the requirements are pure data, can not exist rich text form such as pictures.

The following mainly introduces the method of exporting csv under 1

Introduction to php Official Documents


<?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 a complete example


<?php

$name = 'test';
header ( "Content-type:application/vnd.ms-excel" );
header ( "Content-Disposition:filename=".$name.".csv" );
header ('Cache-Control: max-age=0');

// Open PHP File handle, php://output  Represents direct output to the browser 
$fp = fopen('php://output', 'a');  

//  Write BOM Head, prevent garbled code 
fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF)); 

//  Generated test data 
function test()
{
  for ($i=0; $i < 150000; $i++) {
    yield ['name', $i, ' Male '];
  }
}

//  Header 
$headers = [' Name ', ' Age ', ' Gender '];

fputcsv($fp, $headers);

foreach (test() as $value) {
  fputcsv($fp, $value);
}

fclose($fp);
?>

When used in laravel with chunk, all data can be easily and quickly exported.

The above is the whole content of this knowledge point. Thank you for your support to this site.


Related articles: