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)
$stdout = fopen('php://output','w'); // 'stdout' is for CLI, 'output' is for Browser
fputcsv($stdout, array('val,ue1','val"ue2','value3','etc'));
fflush($stdout); // flush for fun :)
fclose($stdout);
^ this outputs CSV to the Browser.
PHP does indeed contain the function you need: fputcsv()
To stream to the browser, use stdout as your "file":
$stdout = fopen('php://stdout','w');
fputcsv($stdout, array('val,ue1','val"ue2','value3','etc'));
fclose($stdout);
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