Search code examples
phpfwritefputcsv

What is the advantages/disadvantages of using fputcsv?


Below code is from the documentation of fputcsv:

<?php
$time_start = microtime(true);
$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);

$time_end = microtime(true);
$time = $time_end - $time_start;
echo "time is: $time";
?> 

time is: 0.0037028789520264
time is: 0.0036959648132324
time is: 0.0037329196929932

why not just use something like the below code? they seemed like they have the same speed? In this way, you control what kind of new line you need to use like \n or \r\n

<?php
$time_start = microtime(true);
$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fwrite($fp, implode(',', $fields) . "\n");
}

fclose($fp);

$time_end = microtime(true);
$time = $time_end - $time_start;
echo "time is: $time";
?> 

time is: 0.0037031173706055
time is: 0.0037119388580322
time is: 0.0036849975585938

DISCLAIMER: I dont know if im using too small number of fields to benchmark


Solution

  • fputcsv is a helper function. Yes you can do it manualy. Under the hood there would probably be some simmelair funtionality. But it is eassier to implement this way and improves readability. You can just throw in the array and don't have to worry about escaping and so on.