Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is my array to csv function correct?

Tags:

php

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)

like image 275
mpen Avatar asked Dec 04 '22 18:12

mpen


2 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);

^ this outputs CSV to the Browser.

like image 56
CodeAngry Avatar answered Dec 10 '22 11:12

CodeAngry


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);
like image 40
Francis Avila Avatar answered Dec 10 '22 11:12

Francis Avila