Php exports a CSV abstract class instance and exports a csv abstract instance
This example describes how to export a CSV abstract class from php and its application. The specific analysis is as follows:
This php export CSV abstract class can calculate the total number of records and the number of records per batch, and export them cyclically. Avoid insufficient memory.
The ExportCSV. class. php class file is as follows:
<? Php/** php Export CSV abstract class. calculate the total number of records and the number of records per batch, and Export them cyclically. * Date: * Author: fdipzone * Ver: 1.0 ** Func: * public setPageSize set the number of records exported in each batch * public setExportName set the exported file name * public setSeparator set the delimiter * public setDelimiter set the delimiter * public export execute export * private getPageCount calculate the total number of exported batches * private setHeader setting export file header * private formatCSV format data to csv format * private escape string * abstract getExportTotal get the total number of records, abstract method, which must inherit the class implementation * abstract getExportFields get and export Column name, abstract method, inheritance class implementation * abstract getExportData to obtain records per page, abstract method, you need to inherit the class implementation */abstract class ExportCSV {// class start // define the method that the subclass must implement/** get the total number of records * @ return int */abstract protected function getExportTotal (); /** get the exported column name * @ return Array */abstract protected function getExportFields (); /** get data of each batch * @ param int $ offset * @ param int $ number of records obtained by limit * @ return Array */abstract protected function getExportData ($ o Ffset, $ limit); // defines the class attribute protected $ total = 0; // The total number of records protected $ pagesize = 500; // Number of exported records per batch protected $ exportName = 'export.csv '; // exported file name protected $ separator =', '; // set the separator protected $ delimiter = '"'; // set the delimiter/** set the number of records exported each time * @ param int $ pagesize the number of records exported each time */public function setPageSize ($ pagesize = 0) {if (is_numeric ($ pagesize) & $ pagesize> 0) {$ this-> pagesize = $ pagesize ;}}/** set the exported file name * @ Param String $ file name exported by filename */public function setExportName ($ filename) {if ($ filename! = '') {$ This-> exportName = $ filename;}/** set the separator * @ param String $ separator */public function setSeparator ($ separator) {if ($ separator! = '') {$ This-> separator = $ separator;}/** set the delimiter * @ param String $ delimiter */public function setDelimiter ($ delimiter) {if ($ delimiter! = '') {$ This-> delimiter = $ delimiter;}/** export csv */public function export () {// obtain the total number of records $ this-> total = $ this-> getExportTotal (); // if (! $ This-> total) {return false;} // calculate the total number of exported batches $ pagecount = $ this-> getPageCount (); // get the exported column name $ fields = $ this-> getExportFields (); // set the exported file header $ this-> setHeader (); // cyclically export for ($ I = 0; $ I <$ pagecount; $ I ++) {$ exportData = ''; if ($ I = 0) {// export the column name $ exportData before the first record. = $ this-> formatCSV ($ fields);} // sets the offset value $ offset = $ I * $ this-> pagesize; // get the data per page $ data = $ this-> getExportData ($ offset, $ this-> pagesize); // set the data per page Convert data to csv format if ($ data) {foreach ($ data as $ row) {$ exportData. = $ this-> formatCSV ($ row) ;}// export data echo $ exportData ;}/ ** Calculate total batches */private function getPageCount () {$ pagecount = (int) ($ this-> total-1)/$ this-> pagesize) + 1; return $ pagecount ;} /** set the exported file header */private function setHeader () {header ('content-type: application/x-msexcel '); $ ua = $ _ SERVER ['HTTP _ USER_AGENT ']; if (preg_match ("/MSIE/", $ ua)) {Header ('content-disposition: attachment; filename = "'. rawurlencode ($ this-> exportName ). '"');} elseif (preg_match ("/Firefox/", $ ua) {header (" content-disposition: attachment; filename * = \ "utf8 ''". $ this-> exportName. '"');} else {header ('content-disposition: attachment; filename = "'. $ this-> exportName. '"');} ob_end_flush (); ob_implicit_flush (true);}/** format data in csv format * @ param Array $ data to be converted to an Array in csv format */pri Vate function formatCSV ($ data = array () {// escape each element of the array $ data = array_map (array ($ this, 'escape '), $ data ); return $ this-> delimiter. implode ($ this-> delimiter. $ this-> separator. $ this-> delimiter, $ data ). $ this-> delimiter. "\ r \ n";}/** escape String * @ param String $ str * @ return String */private function escape ($ str) {return str_replace ($ this-> delimiter, $ this-> delimiter. $ this-> delimiter, $ str) ;}// class end ?>
The demo sample program is as follows:
<? Php // ExportCSV abstract class require "ExportCSV. class. php "; // defines the inherited class myexport extends ExportCSV {// The data to be exported. The actual situation will read protected $ data = array ('1 ', 'snow star maple "', 'male'), array ('2', 'snow star maple", "', 'male'), array ('3 ', 'snow star maple "," ', 'male'), array ('4', "Snow star maple \" \ "\ r \ n line feed", 'male '), array ('5', 'snow star maple, ', 'male'), array ('6', 'snow star maple "', 'male '), array ('7', 'snow start', 'male'), array ('8', 'snow start', 'mal'), array ('9 ', 'snow start', 'male'), array ('10', 'snow start', 'male ') );/* Total Number of exported records returned * @ return int */protected function getExportTotal () {return count ($ this-> data );} /** return the exported column name * @ return Array */protected function getExportFields () {$ title = array ('id', 'name', 'gender '); return $ title ;} /* return records of each batch * @ param int $ offset * @ param int $ number of records obtained by limit * @ return Array */protected function getExportData ($ offset, $ limit) {return array_slice ($ this-> data, $ offset, $ Limit) ;}/// export $ obj = new myexport (); $ obj-> setPageSize (1); $ obj-> setExportName('myexport.csv '); $ obj-> setSeparator (','); $ obj-> setDelimiter ('"'); $ obj-> export ();?>
Click here to download the complete instance code.
I hope this article will help you with PHP programming.
Source code PHP export data to csv files
<? Php
$ DB_Server = "localhost ";
$ DB_Username = "root ";
$ DB_Password = "";
$ DB_DBName = "DBName ";
$ DB_TBLName = "DB_TBLName ";
$ Savename = date ("YmjHis ");
$ Connect = @ mysql_connect ($ DB_Server, $ DB_Username, $ DB_Password) or die ("Couldn't connect .");
Mysql_query ("Set Names 'gbk '");
$ File_type = "vnd. ms-excel ";
$ File_ending = "xls ";
Header ("Content-Type: application/$ file_type; charset = gbk ");
Header ("Content-Disposition: attachment; filename =". $ savename. ". $ file_ending ");
// Header ("Pragma: no-cache ");
$ Now_date = date ("Y-m-j H: I: s ");
// $ Title = "Database Name: $ DB_DBName, data table: $ DB_TBLName, backup date: $ now_date ";
$ SQL = "Select * from $ DB_TBLName ";
$ ALT_Db = @ mysql_select_db ($ DB_DBName, $ Connect) or die ("Couldn't select database ");
$ Result = @ mysql_query ($ SQL, $ Connect) or die (mysql_error ());
// Echo ("$ title \ n ");
$ Sep = "\ t ";
For ($ I = 0; $ I <mysql_num_fields ($ result); $ I ++ ){
Echo mysql_field_name ($ result, $ I). "\ t ";
}
Print ("\ n ");
$ I = 0;
While ($ row = mysql_fetch_row ($ result )){
$ Schema_insert = "";
For ($ j = 0; $ j <mysql_num_fields ($ result); $ j ++ ){
If (! Isset ($ row [$ j])
$ Schema_insert. = "NULL". $ sep;
Elseif ($ row [$ j]! = "")
$ Schema_insert. = "$ row [$ j]". $ sep;
Else
$ Schema_insert... the remaining full text>
Php generates a csv file and prompts to save it
As you do, you have to have the user upload the previous csv file at the same time.
Or you can save the latest csv files of different users on the server.