PHP 8.4: CSV: The $escape
parameter must be provided
PHP provides built-in CSV functionality, that allows reading and writing to CSV files. This implementation has problematic escaping behaviors that are being slowly phased out.
The CSV functionality uses three characters to separate (,
by default), enclose ("
by default), and escape (\
by default currently). Usually, if the enclose
character is found in the data field, it is escaped by doubling it. However, PHP's implementation allows for the customization of escape behavior by specifying the escape character.
When the escape character is set to any value other than an empty string, or the enclose character itself, it leads to non-compliant and buggy behavior in ways that data can't survive a read-write round-trip such as fgetcsv
-> fputcsv
-> fgetcsv
.
The following functions and methods are affected:
fputcsv
fgetcsv
str_getcsv
SplFileObject::setCsvControl
SplFileObject::getCsvControl
SplFileObject::fputcsv
SplFileObject::fgetcsv
All of the functions/methods listed above have \"
as the default $escape
parameter value.
To gradually phase-out the escape mechanism, PHP 8.4 deprecates not passing the $escape
parameter, and PHP 9.0 plans to remove the $escape
parameter altogether.
This means all the function/method usages above will emit a deprecation notice if the $escape
parameter is not passed by position or as a named parameter.
For example, the str_getcsv
function has the following signature:
str_getcsv(string $string, string $separator = ',', string $enclosure = '"', string $escape = '\\'): array
When using all of the functions above in PHP 8.4 and later, not passing the $escape
parameter emits a deprecation notice:
str_getcsv($string, separator: ',', enclosure: '"');
str_getcsv(): the $escape parameter must be provided as its default value will change ...
To avoid the deprecation notice, explicitly pass the $escape
parameter:
- str_getcsv($string, separator: ',', enclosure: '"');
+ str_getcsv($string, separator: ',', enclosure: '"', escape: "");
It is recommended to use an empty string ""
as the escape character. This effectively disables the escaping mechanism, and PHP continues to escape the $enclosure
character by doubling it if it's encountered in the field data.
Backward Compatibility Impact
In PHP 8.4, not passing the $escape
parameter emits a deprecation notice. Passing the $escape
parameter explicitly avoids the deprecation notice.
PHP 9.0 plans to remove the $escape
parameter altogether, and will always escape the enclosure character by doubling it.