Hi everybody!

There are several bug reports regarding "broken" fputcsv() behavior in
our tracker, namely, because the $escape parameter causes unexpected
results.  For instance:

    <?php
    $row = ['a\\"', 'bbb'];

    $fp = fopen('php://memory', 'w+');
    fputcsv($fp, $row);
    rewind($fp);
    echo stream_get_contents($fp);
    fclose($fp);
    ?>

outputs

    "a\"",bbb

instead of the expected

    "a\""",bbb

I don't think the current behavior is a bug, but rather the escape
character is an extension to the CSV "standard" (RFC 7111).  One can
practically disable the escape character by passing any character that
is not contained in any of the strings in the array; "\0" is usually a
good choice, so changing line 5 in the script above to the following
gives the desired behavior:

    fputcsv($fp, $row, ',', '"', "\0");

Cf. <https://3v4l.org/InlUv> vs. <https://3v4l.org/tVFBo>.

It is, however, not possible to pass an empty string as $escape
argument, because fputcsv() bails out in this case raising

  Warning: fputcsv(): escape must be a character

I suggest to allow an empty string instead, and to consider making this
the default in a future version, probably after some time of deprecating
any other $escape argument.

Thoughts?

-- 
Christoph M. Becker

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to