php-src icon indicating copy to clipboard operation
php-src copied to clipboard

Unexpected behavior when parsing csv

Open stefket opened this issue 4 years ago • 1 comments

Description

The following code:

<?php

$tempFile = __DIR__ . '/temp.csv';

$dataBefore = ['foo', 'foo\\'];

$handle = fopen($tempFile, 'w');
fputcsv($handle, $dataBefore);
fclose($handle);

$handle = fopen($tempFile, 'r');
$dataAfter = fgetcsv($handle);
fclose($handle);

unlink($tempFile);

var_dump($dataBefore === $dataAfter);

Resulted in this output:

false

But I expected this output instead:

true

PHP Version

Tested with 7.4 / 8.0 / 8.1

Operating System

Tested with Ubuntu 20.04 and Mac OS

stefket avatar Feb 14 '22 09:02 stefket

The trailing linebreak after reading is caused by the proprietary escape mechanism; I don't think we can "fix" the behavior for BC reasons. However, as of PHP 7.4.0, you can pass an empty string as $escape which yields the desired behavior:

$dataAfter = fgetcsv($handle, null, ",", "\"", "");

cmb69 avatar Feb 14 '22 10:02 cmb69