使用 fputcsv 的 advantages/disadvantages 是什么?
What is the advantages/disadvantages of using fputcsv?
以下代码来自 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
为什么不使用类似下面的代码呢?他们似乎有相同的速度?通过这种方式,您可以控制需要使用哪种换行符,例如 \n
或 \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
fputcsv 是一个辅助函数。是的,你可以手动完成。在引擎盖下可能会有一些 simmelair 功能。但是这样实现起来更容易,提高了可读性。直接丢数组就可以了,不用担心转义等问题
以下代码来自 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
为什么不使用类似下面的代码呢?他们似乎有相同的速度?通过这种方式,您可以控制需要使用哪种换行符,例如 \n
或 \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
fputcsv 是一个辅助函数。是的,你可以手动完成。在引擎盖下可能会有一些 simmelair 功能。但是这样实现起来更容易,提高了可读性。直接丢数组就可以了,不用担心转义等问题