How to read or export CSV files in PHP
PHP how to read or export CSV files, I believe that many inexperienced people do not know what to do, so this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.
/ * * read CSV file * @ param string $csv_file csv file path * @ param int $lines read lines * @ param int $offset starting lines * @ return array | 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 ($iTunes +)
< $offset) { continue; } break; } $data = array(); while (($j++ < $lines) && !feof($fp)) { $data[] = fgetcsv($fp); } fclose($fp); return $data;}/** * 导出CSV文件 * @param array $data 数据 * @param array $header_data 首行数据 * @param string $file_name 文件名称 * @return string */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 line data * @ param string $file_name file name * @ return string * / public function export_csv_2 ($data = [], $header_data = [], $file_name =') {header ('Content-Type: application/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 ('utf-8',' gbk', $value);} fputcsv ($fp, $header_data);} $num = 0 / / refresh the output buffer every $row, not too big or too small $limit = 1000000; / / fetch data line by line without wasting memory $count = count ($data); if ($count > 0) {for ($I = 0; $I)
< $count; $i++) { $num++; //刷新一下输出buffer,防止由于数据过多造成问题 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);} after reading the above, have you mastered how to read or export CSV files in PHP? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!