str_getcsv()
函数旨在在CSV文本的行上工作,而不是在一组行上工作。我试图使用它两次,一次将多行CSV拆分为一行行,然后在每行上再次。此解决方案对我有效,甚至对I supplied it as an answer to another question也是有效的。
但是,我现在遇到一个问题,行"AC150AC,",service tool,845.71,-2
返回为AC150AC,,service tool,845.71,-2
,并删除了引号,因此逗号现在被视为分隔符。在调试中,我发现多行值现在也无法正常工作,并且尽管正确封装了,但现在仍在中间拆分。
我该如何调试呢?
$ cat csv.php
<?php
$csv = '130,TEST A 1258 (U10 001),28.66,2
"AC150AC,",service tool,845.71,-2
AL7951,SEA LION,47.19,2
T11,"Test multi-
line segments",587.36,4';
$n = str_getcsv($csv, "\n");
$r = str_getcsv($csv, "\r");
print_r($n);
print_r($r);
$ xxd csv.php
00000000: 3c3f 7068 700a 0a24 6373 7620 3d20 2731 <?php..$csv = '1
00000010: 3330 2c54 4553 5420 4120 3132 3538 2028 30,TEST A 1258 (
00000020: 5531 3020 3030 3129 2c32 382e 3636 2c32 U10 001),28.66,2
00000030: 0a22 4143 3135 3041 432c 222c 7365 7276 ."AC150AC,",serv
00000040: 6963 6520 746f 6f6c 2c38 3435 2e37 312c ice tool,845.71,
00000050: 2d32 0a41 4c37 3935 312c 5345 4120 4c49 -2.AL7951,SEA LI
00000060: 4f4e 2c34 372e 3139 2c32 0a54 3131 2c22 ON,47.19,2.T11,"
00000070: 5465 7374 206d 756c 7469 2d0a 6c69 6e65 Test multi-.line
00000080: 2073 6567 6d65 6e74 7322 2c35 3837 2e33 segments",587.3
00000090: 362c 3427 3b0a 0a24 6e20 3d20 7374 725f 6,4';..$n = str_
000000a0: 6765 7463 7376 2824 6373 762c 2022 5c6e getcsv($csv, "\n
000000b0: 2229 3b0a 2472 203d 2073 7472 5f67 6574 ");.$r = str_get
000000c0: 6373 7628 2463 7376 2c20 225c 7222 293b csv($csv, "\r");
000000d0: 0a0a 7072 696e 745f 7228 246e 293b 0a70 ..print_r($n);.p
000000e0: 7269 6e74 5f72 2824 7229 3b0a 0a rint_r($r);..
$ php csv.php
Array
(
[0] => 130,TEST A 1258 (U10 001),28.66,2
[1] => AC150AC,,service tool,845.71,-2
[2] => AL7951,SEA LION,47.19,2
[3] => T11,"Test multi-
[4] => line segments",587.36,4
)
Array
(
[0] => 130,TEST A 1258 (U10 001),28.66,2
"AC150AC,",service tool,845.71,-2
AL7951,SEA LION,47.19,2
T11,"Test multi-
line segments",587.36,4
)
答案 0 :(得分:2)
问题是您要按行末字符(各种类型)将其拆分,而这些字符是中间行还是真正的行末。
使用fgetcsv()
为您完成工作是一种错误,因此您首先必须给它一个文件以供使用。此代码创建一个临时文件,将内容写入其中,然后倒回该文件,以便从头开始读取...
$fh = tmpfile();
fwrite($fh, $csv);
fseek($fh, 0);
while ( $row = fgetcsv($fh)) {
print_r($row);
}
fclose($fh);
答案 1 :(得分:0)
预期结果是什么?我不确定您想要什么。
我想explode()会帮助您吗?
$csv = '130,TEST A 1258 (U10 001),28.66,2
"AC150AC,",service tool,845.71,-2
AL7951,SEA LION,47.19,2
T11,"Test multi-
line segments",587.36,4';
$n = explode("\n", $csv);
var_dump(array_map('str_getcsv', $n));