【问题标题】:Detect if a row read in by fgetcsv is the last row of the csv file with PHP 7.4使用 PHP 7.4 检测 fgetcsv 读入的行是否是 csv 文件的最后一行
【发布时间】:2021-06-29 12:51:56
【问题描述】:

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

$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); 尝试过,但是没有用。有人对如何做到这一点有任何想法吗?

【问题讨论】:

  • 你需要实现什么?如果应该在循环完成后处理,将$myService 移到while 循环之外呢?
  • @pavel,反过来想如果是最后一行则通过
  • 你无法判断哪一行是循环内的最后一行,除非你提前知道会有多少行。
  • 我想将一个巨大的产品 csv 文件导入商店,因此我不想将整个文件加载到 RAM。所以我必须逐行处理,但我需要知道何时到达最后一行。
  • 最后一行有什么特别之处需要进行不同的处理?

标签: php csv fgetcsv


【解决方案1】:

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

$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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    相关资源
    最近更新 更多