Websites often need to export data. Common formats include CSV, XLS, and XML waiting formats.
CSV is a common data format that is connected by multiple commas. It has some advantages over XLS data.
Two ways to export data:
1. When the user triggers the operation, a CSV file is generated on the server side for the user to download.
2. When a user triggers an operation, the client uses the HTTP header information in combination with PHP to generate a CSV file for download.
The first method is to generate a CSV file on the server for each download. If it takes a long time, there will be more and more CSV files on the server, which will be inconvenient to maintain in the future.
In the second implementation mode, without optimization, if the data volume is large, the generation of CSV will be slow, and data may be lost due to network and other reasons.
Simple implementation of the first component:
<? Php
$ Fp = fopen ("test.csv", 'W + '); // generate a CSV file
$ Head_title = array ('report name', 'operator ', 'export Time ');
Fputcsv ($ fp, $ head_title); // generate a report header,
Fclose ($ fp); // close the operation File
?>
Method 2
<? Php
/**
Gzip Compression
**/
Function ob_gzip ($ content)
{
If (! Headers_sent () & extension_loaded ("zlib") & strstr ($ _ SERVER ["HTTP_ACCEPT_ENCODING"], "gzip "))
{
$ Content = StringHelper: Encoding ($ content, 'utf-8', 'gbk ');
$ Content = gzencode ($ content, 9 );
Header ("Content-Encoding: gzip ");
Header ("Vary: Accept-Encoding ");
Header ("Content-Length:". strlen ($ content ));
}
Return $ content;
}
Function export_csv ($ data = NULL)
{
Using down_file='test.csv ';
Header ("Content-Type: text/csv; charset = UTF-8 ");
Header ("Content-Disposition: attachment; filename = $ down_name ");
Header ('cache-Control: must-revalidate, post-check = 0, pre-check = 0 ');
Header ('expires: 0 ');
Header ('pragma: public ');
Ob_start ('ob _ gzip '); // compress the output data to reduce the waiting time for downloading.
// Ob_start (array (& $ this, 'ob _ gzip '));
Echo "report name, operator, export time \ n ";
Ob_end_flush (); // end Compression
}
?>
Tested: the size of the original GZIP page is 20.61 KB (21,101 bytes)
After data compression is used, the page size is 0.23 KB (236 bytes)