php getcount_php 读取文件某一行数据

namespace App\Service;

/**

* Class LogViewService

* @package App\Service

*/

class View extends BaseService

{

/**

* 文件得总行数

* @param $file

* @param int $length

* @return bool|int

*/

public function getCount($file, $length = 40960)

{

$i = 1; // 行数

$handle = fopen($file, "r");

if (!$handle) {

$this->errCode = -1;

$this->errMessage = $file . '日志文件不存在';

return false;

}

while (!feof($handle)) {

fgets($handle, $length);

$i++;

// 不要让文件一直循环下去,但理论上,一个文件行数不会超过一万行

if ($i > 10000) {

break;

}

}

fclose($handle);

return $i;

}

/**

* 获取某个文件中从第几行到第几行得数据

* @param $file

* @param $start

* @param $end

* @param int $length

* @return array|bool

*/

public function getLineContent($file, $start, $end, $length = 40960)

{

$returnTxt = null; // 初始化返回

$i = 1; // 行数

if (!is_file($file)) {

$this->errCode = -1;

$this->errMessage = $file . '日志文件不存在';

return false;

}

$handle = fopen($file, "r");

$data = [];

while (!feof($handle)) {

$buffer = fgets($handle, $length);

if ($i >= $start && $i <= $end) {

$data[] = ($buffer);

}

if ($i > $end) {

break;

}

$i++;

}

fclose($handle);

if (empty($data)) {

$this->errMessage = '没有这么多的日志数据,只有' . $this->getCount($file) . '条数据';

$this->errCode = -20;

return false;

}

return $data;

}

}

使用

$date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

$start = isset($_GET['start']) ? $_GET['start'] : 1;

$end = isset($_GET['end']) ? $_GET['end'] : 2;

// $date = isset($_GET['date']) ? $_GET['date'] : '2019-04-15';

$file = BASE_PATH . '/storage/log/' . $date . '.log';

$count = $this->logView->getCount($file);

$content = $this->logView->getLineContent($file, $start, $end);

if (!$content) {

return $this->responseError($this->logView->getErrMessage(), $this->logView->getErrCode());

}

dump($count);

dd($content);

9ccc40063d53

image.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值