php 導(dǎo)出CSV表格的抽象類
Jun 20, 2016 pm 01:00 PMphp 導(dǎo)出CSV表格的抽象類
php 導(dǎo)出CSV抽象類,根據(jù)總記錄數(shù)與每批次記錄數(shù),計算總批次,循環(huán)導(dǎo)出。避免內(nèi)存不足的問題。
ExportCSV.class.php
<?php /** php Export CSV abstract class,根據(jù)總記錄數(shù)與每批次記錄數(shù),計算總批次,循環(huán)導(dǎo)出。 * Date: 2014-05-16 * Author: fdipzone * Ver: 1.0 * * Func: * public setPageSize 設(shè)置每批次導(dǎo)出的記錄條數(shù) * public setExportName 設(shè)置導(dǎo)出的文件名 * public setSeparator 設(shè)置分隔符 * public setDelimiter 設(shè)置定界符 * public export 執(zhí)行導(dǎo)出 * private getPageCount 計算導(dǎo)出總批次 * private setHeader 設(shè)置導(dǎo)出文件header * private formatCSV 將數(shù)據(jù)格式化為csv格式 * private escape 轉(zhuǎn)義字符串 * abstract getExportTotal 獲取總記錄條數(shù),抽象方法,需繼承類實現(xiàn) * abstract getExportFields 獲取導(dǎo)出的列名,抽象方法,需繼承類實現(xiàn) * abstract getExportData 獲取每頁記錄,抽象方法,需繼承類實現(xiàn) */ abstract class ExportCSV{ // class start // 定義子類必須要實現(xiàn)的方法 /** 獲取總記錄條數(shù) * @return int */ abstract protected function getExportTotal(); /** 獲取導(dǎo)出的列名 * @return Array */ abstract protected function getExportFields(); /** 獲取每批次數(shù)據(jù) * @param int $offset 偏移量 * @param int $limit 獲取的記錄條數(shù) * @return Array */ abstract protected function getExportData($offset, $limit); // 定義類屬性 protected $total = 0; // 總記錄數(shù) protected $pagesize = 500; // 每批次導(dǎo)出的記錄數(shù) protected $exportName = 'export.csv'; // 導(dǎo)出的文件名 protected $separator = ','; // 設(shè)置分隔符 protected $delimiter = '"'; // 設(shè)置定界符 /** 設(shè)置每次導(dǎo)出的記錄條數(shù) * @param int $pagesize 每次導(dǎo)出的記錄條數(shù) */ public function setPageSize($pagesize=0){ if(is_numeric($pagesize) && $pagesize>0){ $this->pagesize = $pagesize; } } /** 設(shè)置導(dǎo)出的文件名 * @param String $filename 導(dǎo)出的文件名 */ public function setExportName($filename){ if($filename!=''){ $this->exportName = $filename; } } /** 設(shè)置分隔符 * @param String $separator 分隔符 */ public function setSeparator($separator){ if($separator!=''){ $this->separator = $separator; } } /** 設(shè)置定界符 * @param String $delimiter 定界符 */ public function setDelimiter($delimiter){ if($delimiter!=''){ $this->delimiter = $delimiter; } } /** 導(dǎo)出csv */ public function export(){ // 獲取總記錄數(shù) $this->total = $this->getExportTotal(); // 沒有記錄 if(!$this->total){ return false; } // 計算導(dǎo)出總批次 $pagecount = $this->getPageCount(); // 獲取導(dǎo)出的列名 $fields = $this->getExportFields(); // 設(shè)置導(dǎo)出文件header $this->setHeader(); // 循環(huán)導(dǎo)出 for($i=0; $iformatCSV($fields); } // 設(shè)置偏移值 $offset = $i*$this->pagesize; // 獲取每頁數(shù)據(jù) $data = $this->getExportData($offset, $this->pagesize); // 將每頁數(shù)據(jù)轉(zhuǎn)換為csv格式 if($data){ foreach($data as $row){ $exportData .= $this->formatCSV($row); } } // 導(dǎo)出數(shù)據(jù) echo $exportData; } } /** 計算總批次 */ private function getPageCount(){ $pagecount = (int)(($this->total-1)/$this->pagesize)+1; return $pagecount; } /** 設(shè)置導(dǎo)出文件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); } /** 格式化為csv格式數(shù)據(jù) * @param Array $data 要轉(zhuǎn)換為csv格式的數(shù)組 */ private function formatCSV($data=array()){ // 對數(shù)組每個元素進(jìn)行轉(zhuǎn)義 $data = array_map(array($this,'escape'), $data); return $this->delimiter.implode($this->delimiter.$this->separator.$this->delimiter, $data).$this->delimiter."\r\n"; } /** 轉(zhuǎn)義字符串 * @param String $str * @return String */ private function escape($str){ return str_replace($this->delimiter, $this->delimiter.$this->delimiter, $str); } } // class end ?>
demo
?
<?php // ExportCSV abstract class require "ExportCSV.class.php"; // 定義繼承類 class myexport extends ExportCSV{ // 要導(dǎo)出的數(shù)據(jù),實際情況會從db讀取 protected $data = array( array('1','傲雪星楓"','男'), array('2','傲雪星楓","','男'), array('3','傲雪星楓","','男'), array('4',"傲雪星楓\"\"\r\n換行",'男'), array('5','傲雪星楓,,','男'), array('6','傲雪星楓"','男'), array('7','傲雪星楓','男'), array('8','傲雪星楓','男'), array('9','傲雪星楓','男'), array('10','傲雪星楓','男') ); /* 返回總導(dǎo)出記錄數(shù) * @return int */ protected function getExportTotal(){ return count($this->data); } /** 返回導(dǎo)出的列名 * @return Array */ protected function getExportFields(){ $title = array('id','name','gender'); return $title; } /* 返回每批次的記錄 * @param int $offset 偏移量 * @param int $limit 獲取的記錄條數(shù) * @return Array */ protected function getExportData($offset, $limit){ return array_slice($this->data, $offset, $limit); } } // 導(dǎo)出 $obj = new myexport(); $obj->setPageSize(1); $obj->setExportName('myexport.csv'); $obj->setSeparator(','); $obj->setDelimiter('"'); $obj->export(); ?>
?

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses
