我需要将csv字符串解析为数组。我使用的是php str_getcsv(),在我找到下面的情况之前,它工作得很好。
$line = 'field1,field2,field3,"this is field having backslash at end\",anothersomeval';
$arrField = str_getcsv($line, ",", '"');
echo count($arrField);所以我预计计数应该是5,但它实际上显示了4。我做了谷歌这个问题,但没有找到任何适当的解决办法。我怀疑str_getcsv()是否有问题,尽管我无法找到关于这方面的任何错误报告。
我需要使用正确的csv解析机制,我不能根据字段分隔符分割值,也不能只炸掉字符串.。
对上述代码出错的地方有什么帮助吗?
发布于 2014-11-14 10:58:18
str_getcsv()的第四个参数设置转义字符;默认转义字符是反斜杠。在你的例子中,你是在逃避杜布尔的引用。
如果反斜杠在您的csv字符串中没有特殊意义,并且您希望将它作为一个文字字符来处理,那么可以确保在csv字符串中不会出现的不同转义字符调用str_getcsv(),例如'#',例如:
$arrField = str_getcsv($line, ",", '"', '#');
echo count($arrField);
5发布于 2014-12-09 02:41:15
我也有同样的问题。我用这个带助修复解决了这个问题,它似乎很好,直到在不使用分隔符字符的功能中添加了一个选项。
//messy CSV content
$csvIn = "\"test 1\", \"test 2\", \"test 3\\\", \"test 4\"";
//we will use the ASCII device control 1 character, this should not be in your CSV input
//to make sure it is not, replace all occurrences with an empty string
$csvIn = str_replace("\x11", "", $csvIn);
//convert the csv to array using str_getcsv function and our non-existent delimiter
//make sure the delimiter character is surrounded by double quotes, single quotes will not work
$csvArray = str_getcsv($csvIn, ',', '"', "\x11");
//output the clean results
print_r($csvArray);发布于 2017-02-14 10:59:30
首先,我要说的是@user2395126解决方案是好的。在我建议的注释中,我建议使用另一种方法来定义$csvIn,使用引号而不是双引号作为字符串分隔符,以避免转义每个斜杠:
//CSV content with a backslash as last character
$csvIn = '"test 1", "test 2", "test 3\", "test 4"';其余的解决方案应该是@ that 2395126。
然后,我尝试了另一种方法:在使用str_getcsv()之前只是转义反斜杠。最后,我们得到了一个部分结果,其中包含一个带有双斜杠的数组,而不是一个斜杠。最后一步是必要的。
在这里,我的完整解决方案:
//CSV content with a backslash as last character
$csvIn = '"test 1", "test 2", "test 3\", "test 4"';
// Escape backslashes
$csvIn = str_replace("\\", "\\\\", $csvIn);
$csvArray = str_getcsv($csvIn, ',', '"');
//output partial result, with double slashes
print_r($csvArray);
//replace double slashes with single one
foreach($csvArray as $key => $item) {
$csvArray[$key] = str_replace("\\\\", "\\", $item);
}
//output the clean results
print_r($csvArray);https://stackoverflow.com/questions/26928154
复制相似问题