【问题标题】:What is the fastest way to parse large CSV files into arrays in PHP?在 PHP 中将大型 CSV 文件解析为数组的最快方法是什么?
【发布时间】:2018-02-27 02:15:09
【问题描述】:

我有一些包含大约 285 列的大型 CSV 文件。 文件之间有超过一百万行。

为了解析每一行,我使用了fgets,它工作得很快。 从那里,我尝试在线上使用str_getcsv,平均每行0.001421秒。这听起来并不多,但是一旦你做了 1,000,000 行,那就是 1421 秒或大约 24 分钟。 为了加快这个过程,在尝试解析 CSV 之前,我会尽可能多地与字符串进行比较。如果我的检查认为它无关紧要,那么它会跳过该行。

当我需要索引值对数据进行更高级的比较时,我的问题就出现了。 str_getcsv 是最快的选择,还是有更快的方法将行放入数组? 我的第一个想法是使用explode,但数据有引用值,一些值也包含逗号。 如果这有助于任何解析规则,我只需要一次处理一行。

【问题讨论】:

  • 不要描述代码,贴在问题里

标签: php arrays csv


【解决方案1】:

我最终为自己创建了一个解决方案,但我很好奇是否有其他人可以针对更大的数据集进行测试? 使用str_getcsv 解析行的平均时间为 0.0014 秒。 使用此代码解析平均需要 0.0002 秒。 它肯定可以使用额外的工作来提供更大的灵活性,但是对于带有引用值的简单 CSV,这对我的目的来说很好。

function _csv2array($line) {
  $ret = [0 => '']; //Start with an empty array
  $idx = 0; //First index
  $lastpos = 0; //No commas found yet
  while (($pos = strpos($line, ',', $lastpos)) !== FALSE) { //While we find another comma
    $ret[$idx].= substr($line, $lastpos, $pos-$lastpos); //Add it to our current index
    if (substr($ret[$idx], 0, 1) == '"') { //If we started with a quote
      if (substr($ret[$idx], -1) == '"') { //Are we ending in a quote?
        $qts = substr_count($ret[$idx], '"') % 2; //Are there an even number of quotes?
        if (!$qts) { //If there's an even amount of quotes, safe to close out this field
          $ret[$idx] = trim($ret[$idx], '"'); //Remove the outer quotes
          $ret[++$idx] = ''; //Start the next index
        } else $ret[$idx].= ','; //Still inside a quoted field, don't ignore this comma, append it
      } else $ret[$idx].= ','; //Still inside a quoted field, don't ignore this comma, append it
    } else { //Non quoted field
      $ret[++$idx] = ''; //Advance to next index
    }
    $lastpos = $pos+1; //Start our next search AFTER this comma
  }
  $ret[$idx].= substr($line, $lastpos); //Add whatever's after the last ,
  $ret[$idx] = trim($ret[$idx], "\"\r\n"); //Remove any newlines/surrounding quotes
  return $ret; //Return the array
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多