使用PHP从大型CSV文件中读取多列

3

我需要从一个庞大的CSV文件中读取两列。该CSV文件具有多列,有时可能具有以下属性:

  1. 约25,000行
  2. 包含空格和空行
  3. 不平均(某些列比其他列长)

enter image description here

在上面的示例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文件方面忽略的缺陷?

1个回答

1

首先,如果您将大文件存储在变量中,则读取任何大文件都会消耗内存。您可以查看读取大文件(超过4GB的Unix)

其次,您可以在while循环中输出$buy和$sold,这可能是更有效利用内存的方式,因为这两个变量没有保存在内存中。

最后,在PHP中使用文件寻址方法fseek documentation


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接