Max*_*Max 4 php large-files fgetcsv csv-import
我已经成功编写了一个脚本,该脚本使用 cURL 下载 CSV 文件,然后将 CSV 解析为数组,如下所示:
$rows = array_map(function($a) {
return str_getcsv($a, $delimiter);
}, explode("\n", $result));
Run Code Online (Sandbox Code Playgroud)
然后我迭代$rows使用foreach将某些内容保存到数据库中。
该脚本运行良好,但是当使用较大的 CSV 文件(> 10.000 行)时,脚本会变得相当慢并且会出现更多错误。
我想将 CSV 文件分成几部分,所以不是整个文件都会被导入到一个变量中。我找到了以下解决方案,但它仍然一次处理整个文件。
有没有一种方法可以将CSV切成碎片并多次运行数据库功能?或者有没有更好的方法来处理这样的大型 CSV 文件?
我对处理大文件比较陌生,所以请多多关照!
将文件保存在某处,然后像这样分块处理它:
<?php
$filePath = 'big.csv';
//How many rows to process in each batch
$limit = 100;
$fileHandle = fopen($filePath, "r");
if ($fileHandle === FALSE)
{
die('Error opening '.$filePath);
}
//Set up a variable to hold our current position in the file
$offset = 0;
while(!feof($fileHandle))
{
//Go to where we were when we ended the last batch
fseek($fileHandle, $offset);
$i = 0;
while (($currRow = fgetcsv($fileHandle)) !== FALSE)
{
$i++;
//Do something with the current row
print implode(', ', $currRow)."\n";
//If we hit our limit or are at the end of the file
if($i >= $limit)
{
//Update our current position in the file
$offset = ftell($fileHandle);
//Break out of the row processing loop
break;
}
}
}
//Close the file
fclose($fileHandle);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3825 次 |
| 最近记录: |