Is my csv array working correctly?

A PHP function to convert CSV strings to PHP arrays , but not a function for the other way around, 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 that I'm missing? From wikipedia it is basically said that quotes should be escaped with another quote, and that’s almost all there is to it. The .CSV file must be opened in MS Excel.

My primitive tests seem to suggest that they work.

(I repeat it, not return the string, because I'm going to pass it directly to the browser)

+4
source share
3 answers
 $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); 

^ outputs CSV to the browser .

+7
source

PHP really contains 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); 
+6
source

You also need to check if $val $sep contains (i.e. indicate a string if it contains a comma):

 if (strpos($val, $quo) !== false || strpos($val, $sep) !== false) { ... } 

Otherwise, fputcsv() will do the job (but only for the file / stream).

+3
source

Source: https://habr.com/ru/post/1386431/


All Articles