php-src
php-src copied to clipboard
Unexpected behavior when parsing csv
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
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, ",", "\"", "");