Search code examples
phpexport-to-csvfputcsv

fputcsv unexpected behavior


Take a look at this code example:

$store = array('This is something \" "special"!', 'Something else "special"!');
$ff = fopen('/tmp/aaaa.csv', 'w');
fputcsv($ff, $store);
fclose($ff);

It gives as a result this:

"This is something \" ""special""!","Something else ""special""!"

What bothers me is that \" remains unchanged. I would expect it to become \"" or at least "". Am I wrong?

In any case this behavior breaks the csv since, for example, postgresql refuses to import such csv...


Solution

  • fputcsv function by default escapes the backslash character. You can check in the manual $escape_char = "\"

    If you don't want to escape the backslash character then you can specify other character like below:

    fputcsv($ff, $store, ',', '"', '!');
    

    This will give you the desired output.