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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With