无法从具有80K记录的CSV读取数据

问题描述 投票:0回答:1

我正在尝试读取超过80K记录的CSV。不幸的是,我无法实现它。有人可以帮帮我吗?我的CSV大约是100MB,我已将memory_limit增加到128M。

我已将memory_limit增加到128M。我尝试使用以下代码:

 $handle = fopen('products.csv');
  if ($handle !== FALSE) {
      $str ='';
      echo "IN";
      while (($data = fgetcsv($handle)) !== FALSE) {
        $str .= json_encode($data); // add each json string to a string variable, save later
        $array[]=$data;
      }
  }

  fclose($handle);
  $finalJsonString = json_encode($array);
  print_r($finalJsonString);

Output: null

如果您对此有所了解,有人可以帮助我吗?

谢谢

php csv large-files fgetcsv
1个回答
0
投票

要解决大文件的内存使用问题,可以使用生成器。

生成器允许您使用foreach迭代一组数据而无需在内存中构建数组,这可能会导致您超出内存限制,或者需要相当长的处理时间来生成(source:php.net generators)。

这应该会帮助你:

// the generator
function readCsv($csv)
{
    $handle = fopen($csv, "r");
    if ($handle) {
        while (!feof($handle)) {
            yield fgetcsv($handle);
        }
        fclose($handle);
    }
}

// initialize variables
$data = [];
$line = null;
$csv = "test.csv"; // change this to the csv-file you want to read
/* 
 * in the foreach do some logic
 * with the yielded csv content
 */
foreach(readCsv($csv) as $line) {
    // show for debug
    echo '<pre>';
    var_dump($line);
    echo '</pre>';
}

// show memory usage
echo "memory peak usage (Kb): " . memory_get_peak_usage()/1024;
© www.soinside.com 2019 - 2024. All rights reserved.