我需要从一个庞大的CSV文件中读取两列。该CSV文件具有多列,有时可能具有以下属性:
- 约25,000行
- 包含空格和空行
- 不平均(某些列比其他列长)
在上面的示例CSV文件中,我只对“Buy”和“Sell”列(A列和D列)中的代码感兴趣。
我已经编写了下面的代码(警告:它不是非常优雅),以便迭代所有行并仅读取所需的列。 我创建了字符串作为1个大型MYSQL查询的输入(而不是运行许多小型查询)。
<?php
//Increase the allowed execution time
set_time_limit(0);
ini_set('memory_limit','256M');
ini_set('max_execution_time', 0);
//Set to detect the ending of CSV files
ini_set('auto_detect_line_endings', true);
$file = "test.csv";
$buy = $sold = ""; //Initialize empty strings
if (($handle = @fopen($file, "r")) !== FALSE) {
while (($pieces = fgetcsv($handle, 100, ",")) !== FALSE) {
if ( ! empty($pieces[0]) ) {
$buy .= $pieces[0] ." ";
}
if ( ! empty($pieces[3]) ) {
$sold .= $pieces[3] ." ";
}
}
echo "Buy ". $buy ."<br>"; //Do something with strings...
echo "Sold ". $sold ."<br>";
//Close the file
fclose($handle);
}
我的问题是:这是否是执行这样任务的最佳方式?该代码对于较小的测试文件有效,但是否存在我在迭代CSV文件方面忽略的缺陷?