php - 如何逐行处理大型 CSV 文件?

标签 php large-files fgetcsv csv-import

我已经成功编写了一个使用 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/

相关文章:

php - HTML5 网络摄像头捕获显示图片

python - 在多处理中处理大量数据和进程

php - 数据未通过 PHP 完全从 MySQL 导出到 CSV

php fgetcsv 返回所有行

php - 跟踪网站多个页面的信息

javascript - jQuery.ajax 将不需要的参数放入 URL

php - 上传大文件 100MB+ 进度

R:如何在没有 RAM 限制的情况下快速读取大型 .dta 文件

php - 使用 PHP 读取 CSV 文件时字符串长度不正确

php - 在 Chrome 中无效的 JSON,在 Firefox 中没有问题(太奇怪了!)