PHP read and export CSV file, faster than phpexcel faster than 80%, while Phpexcel accounted for memory, in the case of large data, 50,000 only a few seconds, almost do not feel
If the number is a scientific calculation, you can add a ' single quote ' in front
/** * Read CSV file * @param string $csv _file csv file path * @param int $lines Read line number * @param int $offset start line * @return AR Ray|bool */public function Read_csv_lines ($csv _file = ", $lines = 0, $offset = 0) {if (! $fp = fopen ($csv _file, ' R ')) { return false; } $i = $j = 0; while (false!== ($line = fgets ($fp))) {if ($i + + < $offset) {continue; } break; } $data = Array (); while ($j + + < $lines) &&!feof ($fp)) {$data [] = Fgetcsv ($FP); } fclose ($FP); return $data;} /** * Export CSV file * @param array $data data * @param array $header _data first row of data * @param string $file _name file name * @return S Tring */public function export_csv_1 ($data = [], $header _data = [], $file _name = ') {header (' Content-type:application /octet-stream '); Header (' content-disposition:attachment; filename= '. $file _name); if (!empty ($header _data)) {echo iconv (' Utf-8 ', ' gbk//translit ', ' "'. Implode ('", "', $header _data)." \ n "); } foreach ($data as $key = + $value) {$output = array (); $output [] = $value [' id ']; $output [] = $value [' name ']; echo iconv (' Utf-8 ', ' gbk//translit ', ' "'. Implode ('", "', $output)." \ "\ n"); }}/** * Export CSV file * @param array $data data * @param array $header _data first row of data * @param string $file _name file name * @return String */public function export_csv_2 ($data = [], $header _data = [], $file _name = ") {Header (' Content-type:applicati On/vnd.ms-excel '); Header (' content-disposition:attachment;filename= '. $file _name); Header (' cache-control:max-age=0 '); $fp = fopen (' php://output ', ' a '); if (!empty ($header _data)) {foreach ($header _data as $key = + $value) {$header _data[$key] = iconv (' UT F-8 ', ' GBK ', $value); } fputcsv ($fp, $header _data); } $num = 0; Every $limit line, refresh the output buffer, not too big, not too small $limit = 100000; Data is fetched row by line without wasting memory $count = count ($data); if ($count > 0) {for ($i = 0; $i < $counT $i + +) {$num + +; Refresh the output buffer to prevent problems caused by excessive data if ($limit = = $num) {Ob_flush (); Flush (); $num = 0; } $row = $data [$i]; foreach ($row as $key = + $value) {$row [$key] = iconv (' utf-8 ', ' GBK ', $value); } fputcsv ($fp, $row); }} fclose ($FP);}
PHP read and export CSV file