Home >Backend Development >PHP Tutorial >PHP reads csv data line by line into the database
Requirement: Import the csv data exported from the Excel file into the database
The solution is as follows:
// 判断文件是否上传成功 if (empty($_FILES['file1']) && $_FILES['file1']['error'] != 0) { return 'Error file1'; } else { $filename = $_FILES['file1']['tmp_name']; } // 组装数据 $fields = ['name', 'age', 'telephone']; $fields_cnt = count($fields); // 用二进制打开文件,避免编码问题 $fp_in = @fopen($filename, "rb"); while (!feof($fp_in)) { $line = fgets($fp_in); if ($line) { $arr = explode(',', $line); // 待插入数据格式化 $fmt = array_map(function ($v) {return ($v == 0) ? $v : ((int) $v);}, $arr); $data[] = array_combine($fields, array_splice($fmt, 1, $fields_cnt)); } } fclose($fp_in); // TP数据批量入库 $q = M("excel_1")->addAll($data);
Summary:
File operation function series: fopen,feof,fgets,fclose respectively open, find, fetch, close Data, formatting can automatically remove the "symbol
array_combine key value merging array.
Related recommendations:
The above is the detailed content of PHP reads csv data line by line into the database. For more information, please follow other related articles on the PHP Chinese website!