工作中,經(jīng)常用到需要將大量數(shù)據(jù)導(dǎo)出的場(chǎng)景乃戈,而大數(shù)據(jù)量的導(dǎo)出褂痰,csv比之excel速度更快,文件更小症虑,更滿足需求缩歪。
以下是一個(gè)csv文件導(dǎo)出類,綜合考慮了系統(tǒng)內(nèi)存谍憔,文件格式等各類問(wèn)題
class Csv
{
? ? private static $_instance = NULL;
? ? private static $_pointer = null;
? ? private function __construct()
{
}
? ? public static function getInstance() {
? ? ? ? if (is_null(self::$_instance)) {
? ? ? ? ? ? self::$_instance = new Csv();
? ? ? ? }
? ? ? ? return self::$_instance;
? ? }
? ? private function __clone()
{
? ? ? ? // TODO: Implement __clone() method.
? ? }
? ? public static function initCsv($filename, $head) {
? ? ? ? ob_clean();
? ? ? ? header('Content-type: text/csv; charset=UTF-8');
? ? ? ? header('Content-Disposition: attachment; filename="' . $filename . '.csv"'); //指定下載文件的描述
? ? ? ? header("Content-Type: application/force-download");
? ? ? ? // 添加bom頭匪蝙,避免excel打開(kāi)文件亂碼
? ? ? ? $bom? = pack("H*", 'EFBBBF');
? ? ? ? self::$_pointer? = fopen("php://output", "w");
? ? ? ? fwrite(self::$_pointer, $bom);
? ? ? ? fputcsv(self::$_pointer, $head);
? ? }
? ? public static function makeCsvByStep($items) {
? ? ? ? foreach ($items as $item) {
? ? ? ? ? ? // 長(zhǎng)數(shù)字處理
? ? ? ? ? ? foreach ($item as &$val) {
? ? ? ? ? ? ? ? $val = "\t" . $val;
? ? ? ? ? ? }
? ? ? ? ? ? fputcsv(self::$_pointer, $item);
? ? ? ? ? ? ob_flush();
? ? ? ? ? ? flush();
? ? ? ? }
}
? ? public static function exportCsv() {
? ? ? ? fclose(self::$_pointer);
? ? ? ? exit;
? ? }
}
推薦:?浮生無(wú)事的博客