无法从具有8万条记录的CSV中读取数据

时间:2019-03-29 14:43:01

标签: php csv large-files fgetcsv

我正在尝试读取具有超过8万条记录的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

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

谢谢

1 个答案:

答案 0 :(得分:0)

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

生成器允许您使用foreach遍历一组数据,而无需在内存中构建数组,这可能会导致您超出内存限制,或者需要相当长的处理时间才能生成(来源: 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;
相关问题