Why does str_getcsv not handle escaped quotes correctly when escape character equals enclosure character? [closed]

16 hours ago 2
ARTICLE AD BOX

I'm using PHP 8.1 and trying to parse a CSV string that follows the convention where double quotes are escaped by doubling them (e.g., "a""b" should become a"b). According to the PHP manual, str_getcsv has an escape parameter that defaults to backslash. In my case, the CSV dialect uses the same character for both enclosure and escaping (double quote), so I set the escape character to " as well.

<?php $csv = '"a""b",c'; $data = str_getcsv($csv, escape: '"'); print_r($data);

I expected the output to be:

text

Array ( [0] => a"b [1] => c )

But instead I get:

text

Array ( [0] => a""b [1] => c )

It seems like the double quotes inside the field are not being interpreted as an escaped quote – they just remain as two quotes. I tried the same with fgetcsv and got the same result.

Why does this happen? Is there a way to properly parse such CSV strings where the escape character is the same as the enclosure character in PHP?

sanjay natta's user avatar

3

Read Entire Article