note 96937 added to function.fputcsv

From: Date: Wed, 24 Mar 2010 04:24:58 +0000
Subject: note 96937 added to function.fputcsv
Groups: php.notes 
Request: Send a blank email to php-notes+get-167339@lists.php.net to get a copy of this message
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 ---- Server IP: 203.89.181.186 Probable Submitter: 203.96.151.36 ---- Manual Page -- http://www.php.net/manual/en/function.fputcsv.php Edit -- https://master.php.net/note/edit/96937 Del: integrated -- https://master.php.net/note/delete/96937/integrated Del: useless -- https://master.php.net/note/delete/96937/useless Del: bad code -- https://master.php.net/note/delete/96937/bad+code Del: spam -- https://master.php.net/note/delete/96937/spam Del: non-english -- https://master.php.net/note/delete/96937/non-english Del: in docs -- https://master.php.net/note/delete/96937/in+docs Del: other reasons-- https://master.php.net/note/delete/96937 Reject -- https://master.php.net/note/reject/96937 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#167339) next »