我有这样的CSV文件:
Year,Make,Model,Description,Price
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""","",5000.00
1996,Jeep,Grand Cherokee,"MUST SELL! ""TODAY""
air, moon roof, loaded",4799.00
如何将其转换为二维数组而不会将最后一行放到自己的数组中?
以下是问题的说明(也在此https://3v4l.org/HAJh1上托管):
$s2=<<<EOD
Year,Make,Model,Description,Price
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""","",5000.00
1996,Jeep,Grand Cherokee,"MUST SELL! ""TODAY""
air, moon roof, loaded",4799.00
EOD;
$lines=str_getcsv($s2,"\n");
print_r($lines);
还有所讨论的错误(尽管在撰写本文时,PHP开发人员尚未将其识别为错误):https://bugs.php.net/bug.php?id=55763
有"solutions" out there,但似乎没有一个能解决这个例子。
答案 0 :(得分:1)
str_getcsv()
期望该字符串是一个CSV记录,而不是整个CSV文件。
如果内存中有CSV文件,则可以使用php://memory
将其转换为可以用fgetcsv()
读取的流。这样可以正确解析记录。
<?php
$s2=<<<EOD
Year,Make,Model,Description,Price
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""","",5000.00
1996,Jeep,Grand Cherokee,"MUST SELL! ""TODAY""
air, moon roof, loaded",4799.00
EOD;
$stream = fopen("php://memory", "r+");
fwrite($stream, $s2);
rewind($stream);
while ($row = fgetcsv($stream)) {
print_r($row);
}
如果CSV实际上在文件中,则只需打开文件并使用fgetcsv()
来读取文件即可。