php - 使用 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);
,但那不起作用。有人对如何做到这一点有任何想法吗?
解决方案
与评论相反,我想我毕竟找到了解决方案。这似乎有效:
$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);
}
推荐阅读
- input - 游戏中的关键停止
- json - 如何以角度显示动态json数据?
- javascript - 被 CORS 阻止:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段授权
- c# - 使用 Github Action 验证 .editorconfig 文件
- javascript - 为什么按钮区域没有按我的预期工作?
- javascript - JavaScript 中对象的浅拷贝和深拷贝
- discord - Discord Bot 静音 CMD 崩溃
- android - android studio 不断停止 - Android Studio
- javascript - 无法在javascript nodejs express中将数据从字符串解析为html
- python - Python 在将 JsonL 转换为 CSV 文件时删除 .jsonl 扩展名