PHP:正在寻找引号内str_getcsv换行错误的解决方法
我有这样一个CSV:PHP:正在寻找引号内str_getcsv换行错误的解决方法,php,Php,我有这样一个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"" a
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
如何将其转换为二维数组,而不将最后一行错误地放入自己的数组中?
以下是问题的说明(也在此处托管):
$s2=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);
}
您需要使用fgetcsv()
。如果逐行读取文件,然后使用str_getcsv()
,则字符串中不会有下一行。str_getcsv()
希望字符串仅为文件的一条记录,而不是整个文件。
<?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);
}