PHP has a function for converting CSV strings to PHP arrays, but not a function for vice-versa, so I wrote one:
function echocsv(array $arr, $quo = '"', $sep = ',') {
$escape = $quo . $quo;
foreach($arr as &$val) {
if(strpos($val, $quo) !== false) {
$val = $quo . str_replace($quo, $escape, $val) . $quo;
}
}
echo implode($sep, $arr) . PHP_EOL;
}
Is there anything I'm overlooking? From wikipedia it basically says that quotes should be escaped with another quote, and that's pretty much all there is to it. The .CSV file will need to be openable in MS Excel.
My primitive tests seem to suggest it's working.
(I'm echoing it rather than returning a string because I'm going to stream it right to the browser)