修复不带引号的多行CSV字符串(使用PHP)

时间:2015-05-24 13:11:05

标签: php csv file-io

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

E.g。第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

问:创建所需输出的首选/最干净的方法是什么,最好使用PHP(或awk / sed / Python / Perl / other * 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个字段(在一行上,或在包含多行字符串时分成多行)
  • 如果字符串中有逗号,则字符串周围会有引号 (也适用于多行字符串)
  • 第一列是整数
  • 只有字符串字段才能获得引号

1 个答案:

答案 0 :(得分:0)

这是我目前正在使用的代码。它适用于我(但对我来说),但我觉得它可以用(更多)更有效的方式完成。

<?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);

?>