从csv文件

时间:2015-12-18 14:02:57

标签: php fgetcsv

我正在尝试解析CSV数据,但是当csv以逗号分隔时会挣扎。

函数fgetcsv()也会在十进制数上分割逗号,即使这些字段是封闭的 当从所述csv文件手动复制行并将其用作变量以使用str_getcsv()对其进行解析时,它可以正常工作。

我对其他分隔符没有问题,例如制表符或分号只用逗号。

例如:

$csv_string = '"OUT30045","stuk","16,70","1","1","5,00","0,0400","16,03","10,00","0,0750","15,45"';

print_r(str_getcsv($csv_string));

输出:

Array
(
[0] => OUT30045
[1] => stuk
[2] => 16,70
[3] => 1
[4] => 1
[5] => 5,00
[6] => 0,0400
[7] => 16,03
[8] => 10,00
[9] => 0,0750
[10] => 15,45
)

这就是我想要的以及应该如何。

但是当我尝试直接从CSV文件中读取相同的上述信息时,它也会分割小数值:

$csv_file = "PriceList_ART_comma.csv";
$file = new SplFileObject($csv_file, "r");

$fields = $file->fgetcsv();
print_r($fields);

输出:

Array(
[0] => "OUT30045"
[1] => "stuk"
[2] => "16
[3] => 70"
[4] => "1"
[5] => "1"
[6] => "5
[7] => 00"
[8] => "0
[9] => 0400"
[10] => "16
[11] => 03"
[12] => "10
[13] => 00"
[14] => "0
[15] => 0750"
[16] => "15
[17] => 45"
)

由于我无法控制用户是否上传逗号,制表符或分号分隔文件,我必须让它用于逗号分隔文件。

非常感谢任何帮助。

CSV文件示例:

"ItemCode","Unit","Price","UnitFactor","EntryMethod","Aantal1","Korting1","Nieuwe prijs1","Aantal2","Korting2","Nieuwe prijs2"
"IND300654","stuk","37,99","1","1",,,,,,
"IND300655","stuk","23,95","1","1",,,,,,
"IND300656","stuk","23,95","1","1",,,,,,
"IND300657","stuk","24,25","1","1",,,,,,
"OUT30045","stuk","16,70","1","1","5,00","0,0400","16,03","10,00","0,0750","15,45"
"OUT30055","stuk","39,20","1","1","5,00","0,0400","37,63",,,
"OUT30073","stuk","45,00","1","1","5,00","0,0400","43,20",,,
"OUT30074","stuk","45,00","1","1","5,00","0,0400","43,20",,,

编辑:

我认为它可能与文件本身有关。 我复制了CSV文件的内容并粘贴在记事本中并将其保存为.csv文件。 当我使用这个新文件时,一切正常...... 不知何故原始的CSV文件无法正确读取,可能是因为某种编码?

编辑已解决:

找到了我的问题的原因。原始CSV文件在每个字符后包含一些NULL字符(chr(0))。 因此解析例如“ItemCode”结果类似于“0I0t0e0m0c0o0d0e。在每行上执行str_replace(chr(0),”“,$ string)后,str_getcsv()正常工作。

0 个答案:

没有答案