PHP导入csv

PHP读取csv文件

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function getFileData($file , $type = 1)
{
$res = [];
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] == '用户ID') {
continue;
}

$arr = [];
$arr['test'] = $data[0];


$res[] = $arr;
}

fclose($handle);
return $res;
}

$arr = getFileData('./test.csv');