工作中经常会有遇到导入/导出的需求,下面是常用的方法。
读取CSV文件,可以分页读取,设置读取行数,起始行数即可。导出CSV文件,用两种方法进行实现。
1 /** 2 * 读取CSV文件 3 * @param string $csv_file csv文件路径 4 * @param int $lines 读取行数 5 * @param int $offset 起始行数 6 * @return array|bool 7 */ 8 public function read_csv_lines($csv_file = '', $lines = 0, $offset = 0) 9 {10 if (!$fp = fopen($csv_file, 'r')) {11 return false;12 }13 $i = $j = 0;14 while (false !== ($line = fgets($fp))) {15 if ($i++ < $offset) {16 continue;17 }18 break;19 }20 $data = array();21 while (($j++ < $lines) && !feof($fp)) {22 $data[] = fgetcsv($fp);23 }24 fclose($fp);25 return $data;26 }27 /**28 * 导出CSV文件29 * @param array $data 数据30 * @param array $header_data 首行数据31 * @param string $file_name 文件名称32 * @return string33 */34 public function export_csv_1($data = [], $header_data = [], $file_name = '')35 {36 header('Content-Type: application/octet-stream');37 header('Content-Disposition: attachment; filename=' . $file_name);38 if (!empty($header_data)) {39 echo iconv('utf-8','gbk//TRANSLIT','"'.implode('","',$header_data).'"'."\n");40 }41 foreach ($data as $key => $value) {42 $output = array();43 $output[] = $value['id'];44 $output[] = $value['name'];45 echo iconv('utf-8','gbk//TRANSLIT','"'.implode('","', $output)."\"\n");46 }47 }48 /**49 * 导出CSV文件50 * @param array $data 数据51 * @param array $header_data 首行数据52 * @param string $file_name 文件名称53 * @return string54 */55 public function export_csv_2($data = [], $header_data = [], $file_name = '')56 {57 header('Content-Type: application/vnd.ms-excel');58 header('Content-Disposition: attachment;filename='.$file_name);59 header('Cache-Control: max-age=0');60 $fp = fopen('php://output', 'a');61 if (!empty($header_data)) {62 foreach ($header_data as $key => $value) {63 $header_data[$key] = iconv('utf-8', 'gbk', $value);64 }65 fputcsv($fp, $header_data);66 }67 $num = 0;68 //每隔$limit行,刷新一下输出buffer,不要太大,也不要太小69 $limit = 100000;70 //逐行取出数据,不浪费内存71 $count = count($data);72 if ($count > 0) {73 for ($i = 0; $i < $count; $i++) {74 $num++;75 //刷新一下输出buffer,防止由于数据过多造成问题76 if ($limit == $num) {77 ob_flush();78 flush();79 $num = 0;80 }81 $row = $data[$i];82 foreach ($row as $key => $value) {83 $row[$key] = iconv('utf-8', 'gbk', $value);84 }85 fputcsv($fp, $row);86 }87 }88 fclose($fp);89 }