PHP str_getcsv()
函数用于将CSV字符串解析为数组的函数。
语法
str_getcsv(string,separator,enclosure,escape);
参数
参数 | 说明 | 必须/可选 |
---|---|---|
string | 指定要解析的字符串。默认为逗号 ( , )。 | 必须。 |
separator | 指定字段分隔符。默认为". | 可选 |
enclosure | 指定字段的包围字符。默认为". | 可选 |
escape | 指定转义字符。默认为反斜杠 (\)。 | 可选 |
示例
介绍2个例子,了解PHP str_getcsv()
函数的使用方法。
示例1
创建'data.csv'文件
<?php
//创建'data.csv'文件
$file = array_map('str_getcsv', file('data.csv'));
?>
输出:
其中array_map函数的意思是将回调函数作用到数组中的每一个元素上。
示例2
1.创建"data.csv"文件
id,name,password,status,mobile,add_time,gender,age,uuid
1,张三,123456,1,13122222222,1579142334,1,22,111
2,李四,123456,1,13133333333,1673836735,2,23,222
3,王五,123456,0,13155555555,1736995134,2,24,333
将以上内容其保存到data.csv。2. 创建:testcsv.php
<?php
header("Content-type: text/html; charset=utf-8");
$CSVfp = fopen("data.csv", "r");
if($CSVfp !== FALSE) {
while(! feof($CSVfp)) {
$data = fgetcsv($CSVfp, 1000, ",");
//检测字符串编码,经检测是gb2312编码
$encode = mb_detect_encoding($data[1], array('ASCII','UTF-8','GB2312','GBK','BIG5'));
//转为utf8
$data[1] = iconv('gb2312', 'utf-8', $data['1']);
print_r($data);
}
}
fclose($CSVfp);
?>
输出:
Array ( [0] => id [1] => name [2] => password [3] => status [4] => mobile [5] => add_time [6] => gender [7] => age [8] => uuid ) Array ( [0] => 1 [1] => 张三 [2] => 123456 [3] => 1 [4] => 13122222222 [5] => 1579142334 [6] => 1 [7] => 22 [8] => 111 ) Array ( [0] => 2 [1] => 李四 [2] => 123456 [3] => 1 [4] => 13133333333 [5] => 1673836735 [6] => 2 [7] => 23 [8] => 222 ) Array ( [0] => 3 [1] => 王五 [2] => 123456 [3] => 0 [4] => 13155555555 [5] => 1736995134 [6] => 2 [7] => 24 [8] => 333 ) Array ( [1] => )
上面使用mb_detect_encoding
函数判断字符串编码发现是gb2312,然后使用了iconv
函数将gb2312转为utf8。
示例3
<?php
$str_CSV = '"1","PEN","red"
"2","Book","green"
';
$row = str_getcsv($str_CSV, "\n");
$length = count($row);
for($i=0;$i<$length;$i++) {
$data = str_getcsv($row[$i], ",");
print_r($data);
}
?>
输出:
Array
(
[0] => 1
[1] => PEN
[2] => red
)
Array
(
[0] => 2
[1] => Book
[2] => green
)
Array
(
[0] =>
)
(
[0] => 1
[1] => PEN
[2] => red
)
Array
(
[0] => 2
[1] => Book
[2] => green
)
Array
(
[0] =>
)