php – 读取大文件时出现内存不足错误

前端之家收集整理的这篇文章主要介绍了php – 读取大文件时出现内存不足错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个大的csv,我想解析并插入我的数据库.我有这个 PHP
$target = '../uploads/'.$f;
$handle = fopen($target,"r");
$data = fgetcsv($handle,",");

$rows = array();

while ($data !== FALSE) {
    $rows[] =  $data;
}

fclose($handle);

if (count($rows)) {
             foreach ($rows as $key => $value) {

                  echo $value;

              }
          }

每次我尝试运行我的脚本时都会收到此错误

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 35 bytes)

任何想法如何做到这一点?

我认为这部分是错误的:
$data = fgetcsv($handle,");
$rows = array();
while ($data !== FALSE) {
    $rows[] =  $data;
}

一次调用fgetcsv从$handle中读取一行.你需要把fgetcsv放在循环条件中:

$handle = fopen($target,");
while (($row = fgetcsv($handle,")) !== FALSE) {
    // Example insert - obvIoUsly use prepared statements/escaping/another DAL
    $db->query("INSERT INTO tbl (columns..) VALUES ({$row[0]},{$row[1]} ... )");
}

猜你在找的PHP相关文章