【问题标题】:Reading multiple columns from large CSV files in PHP在 PHP 中从大型 CSV 文件中读取多列
【发布时间】:2014-01-10 18:43:11
【问题描述】:

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

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

在上面的示例 CSV 文件中,我只对“买入”和“卖出”列(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 文件时我是否忽略了一些缺点?

【问题讨论】:

    标签: php csv


    【解决方案1】:

    首先,如果将大文件存储在变量中,则读取任何大文件都会消耗内存。您可以查看reading large files(more than 4GB in unix)

    其次,你可以输出 $buy & $sold 在 while 循环上,这可能会提高内存效率,因为这两个变量不会保存在内存中。

    最后,在php中使用文件查找方法fseek documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-14
      • 2011-07-24
      • 2013-07-05
      相关资源
      最近更新 更多