修复多行CSV字符串没有引号(使用PHP)


fix multi-line CSV string without quotes (using PHP)

我有一个CSV文件,其中带逗号的字符串周围有引号,但没有逗号的字符串周围没有引号。问题是:多行字符串(没有逗号)没有引号。我如何将它们视为一个领域?

。第3-5行多行字符串之间没有引号:

id1,h2,h3,h4
2,2a:with comma and quote / middle field,"3,a
b
c",4a
3,2a:no comma no quote / last field,3a,4a
b
c
4,2a:no comma no quote / middle field,3a
b
c,4a
5,2a:no comma no quote / middle and last field,3a
b
c,4a
b
c

Q:创建所需输出的首选/最干净的方式是什么,最好使用PHP(或awk/sed/Python/Perl/其他*nix CLI工具)?

  • 选项a(首选):在多行字符串
  • 周围加引号
  • 选项b(解决方案):对没有引号的多行字符串使用分隔符(例如|)而不是换行符

选项A:首选-在多行字符串

周围加上引号
id1,h2,h3,h4
2,2a:with comma and quote / middle field,"3,a
b
c",4a
3,2a:no comma no quote / last field,3a,"4a
b
c"
4,2a:no comma no quote / middle field,"3a
b
c",4a
5,2a:no comma no quote / middle and last field,"3a
b
c","4a
b
c"

选项B:变通方法-对没有引号的多行字符串使用分隔符(例如|)而不是换行符

id1,h2,h3,h4
2,2a:with comma and quote / middle field,"3,a
b
c",4a
3,2a:no comma no quote / last field,3a,4a|b|c
4,2a:no comma no quote / middle field,3a|b|c,4a
5,2a:no comma no quote / middle and last field,3a|b|c,4a|b|c

在我的文本文件:

  • 每行总是有4个字段(要么在一行上,要么在包含多行字符串时拆分为多行)
  • 如果字符串中有逗号,则在字符串周围加上引号(也适用于多行字符串)
  • 第一列为整数
  • 只有字符串字段应该用引号括起来

这是我目前使用的代码。这(对我来说)很有效,但我觉得可以用一种(更)有效的方法来做。

<?php
$inputFile = "test.csv"; 
$outputFile = "output.csv";
$in = fopen($inputFile, "r") or die("could not open ".$inputFile);
$out = fopen($outputFile, 'w');
$rowCount = 0;
//column count
$firstLine = fgetcsv($in);
$columnCount = count($firstLine);
fputcsv($out, $firstLine);
$buffer = array();
while ($line = fgetcsv($in) ) {
    $rowCount++;
    // new line: put in buffer
    if (!count($buffer)) {
        $buffer = $line; 
        continue;
    }
    // new line is not starting with number, and not complete
    if (count($line) != $columnCount && !is_numeric($line[0]) ) {
        $first = array_shift($line);
        $buffer[count($buffer)-1] .= "'n". $first;
        $buffer = array_merge($buffer,$line);
    }
    // row is complete
    if (count($line) == $columnCount || (count($line)>0 && is_numeric($line[0]) ) && count($buffer) == $columnCount ) {
        fputcsv($out, $buffer);
        $buffer = $line;
    }
}
// write final buffer
if (count($buffer)) {
    fputcsv($out, $buffer);
}
fclose($in);
fclose($out);
?>