首页 > 解决方案 > 使用 PHP 7.4 检测 fgetcsv 读入的行是否是 csv 文件的最后一行

问题描述

如果当前行是最后一行,是否可以在以下代码示例中检测到?这是我的代码:

$file = \fopen('/path/to/file.csv', 'rb');
while (($row = \fgetcsv($file, 0, ';')) !== false) {
    // Detect if it is the last row
    $isLastRow = ?;

    // Do some stuff for all rows and pass if it is the last row
    $myService->handleRow($row, $isLastRow);
}

我已经尝试过$isLastRow = feof($file);,但那不起作用。有人对如何做到这一点有任何想法吗?

标签: phpcsvfgetcsv

解决方案


与评论相反,我想我毕竟找到了解决方案。这似乎有效:

$fileEndPosition = \filesize('/path/to/file.csv');
$file = \fopen('/path/to/file.csv', 'rb');
while (($row = \fgetcsv($file, 0, ';')) !== false) {
    // Detect current file pointer position
    $currentPosition = ftell($file); 

    // Detect if it is the last row
    $isLastRow = $currentPosition >= $fileEndPosition;

    // Do some stuff for all rows and pass if it is the last row
    $myService->handleRow($row, $isLastRow);
}

推荐阅读