我已经成功编写了一个使用 cURL 下载 CSV 文件的脚本,然后将 CSV 解析为一个数组,如下所示:
$rows = array_map(function($a) {
return str_getcsv($a, $delimiter);
}, explode("\n", $result));
然后我遍历
$rows
使用 foreach
将某些内容保存到数据库中。该脚本运行良好,但是当使用较大的 CSV 文件(> 10.000 行)时,脚本会变得相当慢并且会出现更多错误。
我想将 CSV 文件分成几部分,所以不是整个文件都会被导入到一个变量中。我找到了以下 solution ,但这仍然会立即处理整个文件。
有没有一种方法可以将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);
关于php - 如何逐行处理大型 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45613752/