PHP使用SplFileObject类按行读取文件内容时碰到的问题

PHP Version : 7.2.11
系统类型:windows
代码如下
public function actionTest()
    {
        $path = dirname(Yii::$app->basePath) . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . 'test.log';
        echo $this->getFileLineHandle($path, 0) . '--this is index 0' .  PHP_EOL;
        echo $this->getFileLineHandle($path, 1) . '--this is index 1' .  PHP_EOL;
        echo $this->getFileLineHandle($path, 2) . '--this is index 2' .  PHP_EOL;
        echo $this->getFileLineHandle($path, 3) . '--this is index 3' .  PHP_EOL;
    }

    /**
     * 获取指定行内容
     * @param $fileName
     * @param $linePosition
     * @return false|string
     */
    public function getFileLineHandle($fileName, $linePosition)
    {
        $f = new \SplFileObject($fileName, 'r');
        $f->seek($linePosition);
        try {
            $content = $f->fgets();
        } catch (\Exception $e) {
            // 若是行数超过文件总行数,获取异常
            $content = $e->getMessage();
        }
        return $content;
    }
获取的文件内容(后面跟的就是换行符,总共三行,sublimeText打开)

结果如下
111
--this is index 0
333--this is index 1
Cannot read from file E:\project\huajian\logs\test.log--this is index 2
Cannot read from file E:\project\huajian\logs\test.log--this is index 3
问题所在:读取指针为0时是第一行内容(111),为啥指针为1时读取的是333而不是222呢?
怀疑点:test.log有问题,编辑器查看111后面只有换行没有空格,但是获取行内容时获取出来的有空格,数据长度不是3而是5,蒙了
讨论数量: 2

打印出了指针值和行内容

public function actionTest()
    {
        $path = dirname(Yii::$app->basePath) . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . 'test.log';
        $file = new \SplFileObject($path);
        while (!$file->eof()) {
            echo $file->key() . PHP_EOL;
            echo $file->fgets();
        }
    }

打印内容

0
111
0
222
1
333
2年前 评论
莫须有 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!