CSV 导入:逐行读、批量插、错误可回溯
用 fgetcsv 逐行解析,跳过表头,分批入库,记录每条失败原因,避免一行出错整批回滚。
更新于 2026-11-1457 行代码
完整代码
PHP
<?php
function import_csv(PDO $pdo, string $path, int $batch = 500): array
{
$fh = fopen($path, 'r');
if ($fh === false) {
return ['ok' => 0, 'fail' => 0, 'errors' => ['打不开文件']];
}
$ok = 0;
$fail = 0;
$errors = [];
$rows = [];
$line = 0;
$st = $pdo->prepare('INSERT INTO contacts (name, phone, email) VALUES (?,?,?)');
while (($row = fgetcsv($fh)) !== false) {
$line++;
if ($line === 1) continue; // 跳过表头
if (count($row) < 3 || trim((string)$row[0]) === '') {
$fail++;
$errors[] = "第 {$line} 行:字段不足";
continue;
}
$rows[] = [trim($row[0]), trim($row[1]), trim($row[2])];
if (count($rows) >= $batch) {
[$o, $e] = flush_rows($st, $rows, $line);
$ok += $o;
$fail += $e;
$rows = [];
}
}
if ($rows) {
[$o, $e] = flush_rows($st, $rows, $line);
$ok += $o;
$fail += $e;
}
fclose($fh);
return ['ok' => $ok, 'fail' => $fail, 'errors' => array_slice($errors, 0, 50)];
}
function flush_rows(PDOStatement $st, array $rows, int $line): array
{
$ok = 0;
$fail = 0;
foreach ($rows as $r) {
try {
$st->execute($r);
$ok++;
} catch (PDOException $e) {
$fail++;
}
}
return [$ok, $fail];
}
怎么用
- 上传 CSV 后把临时文件路径传给 import_csv,返回成功与失败条数。
- 表头和字段顺序要固定,导入前给用户一个模板下载。
- 手机号、邮箱这类唯一字段建议先建唯一索引,重复导入会走失败分支。
注意
- CSV 的编码可能是 GBK,读之前用 mb_convert_encoding 转成 UTF-8。
- 大批量导入时把事务按批次提交,比一条一提交快几十倍。
- 错误只保留前 50 条,避免十万行全错时把内存撑爆。