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);
    rewind($buffer);
    $csv = fgets($buffer);
    fclose($buffer);
    return $csv;
}



https://www.electrictoolbox.com/php-fputcsv-without-file/


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

https://joeyxff.blogspot.com/2019/09/phptemp-phpmemory-life-time-php-output.html

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

No comments:

Post a comment