对于数百万条数据量的CSV文件,文件大小可能达到数百M,如果简单读取的话很可能出现超时或者卡死的现象。
为了成功将CSV文件里的数据导入数据库,分批处理是非常必要的。
下面这个函数是读取CSV文件中指定的某几行数据:
复制代码 代码如下:
/**
* csv_get_lines 读取CSV文件中的某几行数据
* @param $csvfile csv文件路径
* @param $lines 读取行数
* @param $offset 起始行数
* @return array
* */
function csv_get_lines($csvfile, $lines, $offset = 0) {
if(!$fp = fopen($csvfile, 'r')) {
return false;
}
$i = $j = 0;
while (false !== ($line = fgets($fp))) {
if($i++ continue;
}
break;
}
$data = array();
while(($j++ $data[] = fgetcsv($fp);
}
fclose($fp);
return $data;
}
调用方法:
复制代码 代码如下:
$data = csv_get_lines('path/bigfile.csv', 10, 2000000);
print_r($data);
函数主要采用行定位的思路,通过跳过起始行数来实现文件指针定位。
上述函数对500M以内的文件进行过测试,运行通畅,对于更大的文件未做测试,请斟酌使用或加以改进。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools