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
打印出了指针值和行内容
打印内容