PHP 8.5.0 Alpha 1 available for testing

Voting

: one minus one?
(Example: nine)

The Note You're Voting On

simeonl at dbc dot co dot nz
15 years ago
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+'); // see http://php.net/manual/en/wrappers.php.php - yes there are 2 '.php's on the end.
// NB: anything you read/write to/from 'php://temp' is specific to this filehandle
}
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;
}

// test
$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

<< Back to user notes page

To Top