Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write CSV data to a variable? [duplicate]

I am reading some data from my database, and I want to convert it into a csv to be displayed. But, I DON'T want to write to a file - is there any way to convert array data into a csv string without using a temporary file?

like image 538
Benubird Avatar asked Mar 15 '26 17:03

Benubird


1 Answers

Yes, there is. It is possible to use php://memory as if it was a file output stream, although it actually only writes to memory, not to a file.

For example, to convert the array $data into csv format $rows:

$rows = array();
$fd = fopen('php://memory','rw');
foreach($data as $datum) {
    fputcsv($fd, $datum);
    rewind($fd);
    $rows[] = trim(fgets($fd));
    rewind($fd);
}
fclose($fd);

Here you can see I open the memory for reading/writing, then for each data set, I write the data as csv - then rewind to the start of the memory - then read the contents of the memory. Note that fputcsv always terminates the line with a newline, which is why I can use fgets to read the line without having to worry about overflow. You may need to change it a bit if you are storing data containing newlines, as fgets won't work then and you'll need to do some more elaborate checking/validation, and the maximum size of php:://memory is defined in php.ini.

like image 176
Benubird Avatar answered Mar 18 '26 06:03

Benubird