In general I found myself wanting to get the result as a string rather than writing it to a file, and in particular I wanted to produce a CSV using an EOL that might not be the same as that on the server where I generated it. This is how I solved the problem without rewriting fputcsv.
<?php
function sputcsv($row, $delimiter = ',', $enclosure = '"', $eol = "\n")
{
static $fp = false;
if ($fp === false)
{
$fp = fopen('php://temp', 'r+'); }
else
{
rewind($fp);
}
if (fputcsv($fp, $row, $delimiter, $enclosure) === false)
{
return false;
}
rewind($fp);
$csv = fgets($fp);
if ($eol != PHP_EOL)
{
$csv = substr($csv, 0, (0 - strlen(PHP_EOL))) . $eol;
}
return $csv;
}
$rows = array
(
array('blue, sky', 'green, lime', 'red', 'black'),
array('white', 'gold', 'purple, imperial', 'grey, slate'),
array('orange, burnt', 'pink, hot', 'violet', 'indigo'),
);
if (PHP_EOL == "\r\n")
{
$eol = "\n";
}
else
{
$eol = "\r\n";
}
foreach($rows as $row)
{
echo nl2br(sputcsv($row, ',', '"', $eol));
}
?>
The test should produce something like the following:
"blue, sky","green, lime",red,black
white,gold,"purple, imperial","grey, slate"
"orange, burnt","pink, hot",violet,indigo