Home  >  Article  >  Backend Development  >  PHP reads csv data line by line into the database

PHP reads csv data line by line into the database

不言
不言Original
2018-04-16 16:06:391487browse


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:

Basic operations for reading data in Php

Example sharing of php reading local json files

PHP reads CSV file data and generates CSV files

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn