Php exports a CSV abstract class instance and exports a csv abstract instance _ PHP Tutorial

Source: Internet
Author: User
Php exports a CSV abstract class instance and a csv abstract instance. Example of exporting CSV abstract classes from php. Examples of exporting csv abstract classes from php and their applications are described in this article. The specific analysis is as follows: This php exports CSV, extracts php, exports CSV abstract class instances, and exports csv abstract instances.

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

$ 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 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.

Examples in this article describes how to export a CSV abstract class from php and its applications. The specific analysis is as follows: This php exports CSV pumping...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.