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
3年前 评论
莫须有 3年前