From 5b3d8566f0b74b2d77c6e993d44ab3fd7f547aa6 Mon Sep 17 00:00:00 2001 From: Krzychu Date: Tue, 13 Sep 2016 12:04:55 +0200 Subject: [PATCH] Properly handle multi line CSV with quotation at end of line --- src/KzykHys/CsvParser/Iterator/CsvIterator.php | 7 ++++--- test/KzykHys/CsvParser/CsvParserTest.php | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/KzykHys/CsvParser/Iterator/CsvIterator.php b/src/KzykHys/CsvParser/Iterator/CsvIterator.php index 72e0e2e..7104741 100644 --- a/src/KzykHys/CsvParser/Iterator/CsvIterator.php +++ b/src/KzykHys/CsvParser/Iterator/CsvIterator.php @@ -85,19 +85,20 @@ public function current() // loop over the columns foreach ($tokens as $value) { $value = preg_replace('/"(\r\n|\r|\n)*$/', '"', $value); + $lastChar = substr($value, -1); + $lastTwoChars = substr($value, -2); // check the first letter is 'enclosure' or not if (substr($value, 0, 1) == $this->option['enclosure']) { // check the last letter is 'enclosure' - if (substr($value, -1) == $this->option['enclosure']) { + if ($lastChar == $this->option['enclosure'] && $lastTwoChars != '\"') { $this->processEnclosedField($value, $this->option); } else { $this->processContinuousField($value, $this->option); } - } else { // first letter is NOT 'enclosure' // check the last letter is 'enclosure' - if(substr($value, -1) == $this->option['enclosure']) { + if ($lastChar == $this->option['enclosure'] && $lastTwoChars != '\"') { $this->processClosingField($value, $this->option); } else { $this->processField($value, $this->option); diff --git a/test/KzykHys/CsvParser/CsvParserTest.php b/test/KzykHys/CsvParser/CsvParserTest.php index d11c7a7..b2ec8fc 100755 --- a/test/KzykHys/CsvParser/CsvParserTest.php +++ b/test/KzykHys/CsvParser/CsvParserTest.php @@ -63,6 +63,23 @@ public function testCompareResultsFromFileAndString($name, array $files, $out) $this->assertEquals($out, $results['CR'], $name . '(CR)'); } + public function testMultiLineWithQuotationAtEndOfLine() + { + //given + $csvString = <<end","asd","" +EOF; + + //when + $parsedCsv = CsvParser::fromString($csvString)->parse(); + + //then + $this->assertEquals('
end
',$parsedCsv[1][1]); + } + /** * @expectedException \InvalidArgumentException */