Wednesday, 11 September 2019

PHP CSV in case returning a string instead of file

 NEVER use explode(). It won't recognize escaped and/or enclosed separator. That's even worse, because explode() will work in most cases, so without proper testing (which is not so simple), you can think that code is working and it will crash in unexpected time, probably, basing on Murphy's law, when you show it to client.

 function array2csv($fields, $delimiter = ",", $enclosure = '"', $escape_char = "\\")
    $buffer = fopen('php://temp', 'r+');
    fputcsv($buffer, $fields, $delimiter, $enclosure, $escape_char);
    $csv = fgets($buffer);
    return $csv;

Recomment use php output stream, as write in memory and temp has size limitation, and other weird issues:

$fp = fopen('php://output', 'w');
fwrite($fp, 'Hello World!'); //User will see Hello World!

No comments:

Post a comment