This article brings you an introduction to the method of reading CSV files in PHP (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Recently, I have done related functions, reading data from CSV format files, and then performing operations. The following is recorded with example code.
fgetcsv
fgetcsv — Reads a line from a file pointer and parses CSV fieldsIf an invalid file pointer is provided, fgetcsv() returns NULL. Other errors include returning FALSE when end-of-file is encountered.
This function is more critical. You can see that its function is to read and parse CSV fields. There are not too many parameters used this time. If necessary, please refer to the link below for your own reference.
Example
The CSV file example is as follows
<?php function getFileData($file) { if (!is_file($file)) { exit('没有文件'); } $handle = fopen($file, 'r'); if (!$handle) { exit('读取文件失败'); } while (($data = fgetcsv($handle)) !== false) { // 下面这行代码可以解决中文字符乱码问题 // $data[0] = iconv('gbk', 'utf-8', $data[0]); // 跳过第一行标题 if ($data[0] == 'name') { continue; } // data 为每行的数据,这里转换为一维数组 print_r($data);// Array ( [0] => tom [1] => 12 ) } fclose($handle); } getFileData('./01.csv');
The above is the detailed content of Introduction to the method of reading CSV files in php (code example). For more information, please follow other related articles on the PHP Chinese website!