PHP Export CSV Abstract class instance, export CSV abstract instance _php tutorial

Source: Internet
Author: User

PHP Export CSV Abstract class instance, export CSV abstract instance


This article describes the PHP export CSV abstract class and its application, share to everyone for your reference. The specific analysis is as follows:

This PHP export CSV abstract class, according to the total number of records and the number of records per batch, calculate the total batch, loop export. Avoid running out of memory problems.

The ExportCSV.class.php class file is as follows:

<?php/** PHP Export CSV abstract class, calculates the total batches based on the total number of records and the number of records per batch, and loops the export. * date:2014-05-16 * author:fdipzone * ver:1.0 * Func: * Public setpagesize set number of records exported per batch * public SETEXPORTN AME set Export filename * Public setseparator Set delimiter * Public Setdelimiter set delimiter * Public export perform export * Private GETPAGEC Ount calculation Export Total batch * Private SetHeader Set Export file header * Private formatcsv Format data in CSV format * Private escape escape String * A Bstract Getexporttotal Get total number of records, abstract method, need to inherit class implementation * Abstract Getexportfields get exported column name, abstract method, need to inherit class implementation * Abstract Getexportdata get each page Record, abstract method, inheriting class implementation */abstract class exportcsv{//Class Start//define subclass must implement method/** get total number of records * @return int */ABS    Tract protected function getexporttotal ();    /** gets the exported column name * @return Array */abstract protected function getexportfields (); /** Get data per batch * @param int $offset offset * @param int $limit number of records obtained * @return Array */abstract protected function    Getexportdata ($offset, $limit); Defining class Properties Protected $total = 0;      Total Record count protected $pagesize = 500; Number of records exported per batch protected $exportName = ' export.csv ';      The exported file name protected $separator = ', ';      Set delimiter protected $delimiter = ' "; Set delimiter/** sets the number of record strips per export * @param int $pagesize Number of record entries per export */Public Function setpagesize ($pagesize =0) {if     _numeric ($pagesize) && $pagesize >0) {$this->pagesize = $pagesize; }}/** set the exported file name * @param String $filename The exported file name */Public Function Setexportname ($filename) {if ($filename     ! = ') {$this->exportname = $filename; }}/** Set delimiter * @param String $separator delimiter */Public Function Setseparator ($separator) {if ($separator! = "     ) {$this->separator = $separator; }}/** Set delimiter * @param String $delimiter delimiter */Public Function Setdelimiter ($delimiter) {if ($delimiter! = "     ) {$this->delimiter = $delimiter; }}/** exports CSV */Public Function export () {//Get total records $this->totaL = $this->getexporttotal ();     No record if (! $this->total) {return false;      }//Calculate export total Batch $pagecount = $this->getpagecount ();      Gets the exported column name $fields = $this->getexportfields ();      Set export file header $this->setheader ();        Loop export for ($i =0; $i < $pagecount; $i + +) {$exportData = ';       The IF ($i ==0) {////first record is exported before the column name $exportData. = $this->formatcsv ($fields);        }//Set offset value $offset = $i * $this->pagesize;        Get data per page $data = $this->getexportdata ($offset, $this->pagesize);         Convert each page of data to CSV format if ($data) {foreach ($data as $row) {$exportData. = $this->formatcsv ($row);     }}//Export data echo $exportData;      }}/** calculates the total batch */Private function Getpagecount () {$pagecount = (int) (($this->total-1)/$this->pagesize) +1;   return $pagecount; }/** set the export 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); }/** formatted data in CSV format * @param array $data to convert to the CSV format */Private Function Formatcsv ($data =array ()) {//each element of the array is entered     Line Escape $data = Array_map (Array ($this, ' escape '), $data); return $this->delimiter.implode ($this->delimiter. $this->separator $this->delimiter, $data). $this- >delimiter. "   \ r \ n "; The/** escaped String * @param string $str * @return String */Private Function Escape ($str) {return Str_replace ($thi   S->delimiter, $this->delimiter. $this->delimiter, $STR); }}//Class enD?>  

The

Demo sample program is as follows:

<?php//Exportcsv abstract class require "ExportCSV.class.php";     Define the inheriting class class Myexport extends exportcsv{//The data to be exported, the actual situation will be read from the db protected $data = Array (' 1 ', ' Proud snow star Maple ', ' male '), Array (' 2 ', ' Proud snow star Maple "," ', ' Male '), Array (' 3 ', ' Proud snow star Maple ', ' ' ', ' ' Male '), Array (' 4 ', "Proud snow star maple \" \ "\ r \ n", ' Male '), Array (' 5 ', ' Proud snow star Maple, ', ' male '), Array (' 6 ', ' Proud snow star Maple ', ' male '), Array (' 7 ', ' Proud snow star Maple ', ' male '), array (' 8 ', ' Proud snow star Maple ', ' male '), Array (' 9 ', ' Proud snow star Maple ', ' male '), array    (' 10 ', ' Proud snow star Maple ', ' Male '));   /* Returns the total number of exported records * @return int */protected function getexporttotal () {return count ($this->data);     /** returns the exported column name * @return Array */protected function Getexportfields () {$title = array (' id ', ' name ', ' gender ');   return $title; }/* Returns records per batch * @param int $offset offset * @param int $limit The number of record bars obtained * @return Array */protected function Gete   Xportdata ($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 ();?>

Full instance code click here to download this site.

I hope this article is helpful to everyone's PHP programming.


SOURCE PHP Export data to CSV file

$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 sheet: $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 ... Remaining full text >>

PHP generates a CSV file and prompts to save

As you do, you also have to let the user upload the previous CSV file

Or you could save the latest CSV file for different users on the server.

http://www.bkjia.com/PHPjc/883680.html www.bkjia.com true http://www.bkjia.com/PHPjc/883680.html techarticle PHP Export CSV abstract class instance, export CSV Abstract instance This article describes the PHP export CSV abstract class and its application, share to everyone for your reference. The specific analysis is as follows: The PHP export 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.