美文网首页
php 读取文件某一行数据

php 读取文件某一行数据

作者: 云龙789 | 来源:发表于2019-04-17 13:51 被阅读0次
    <?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);
    
    image.png

    相关文章

      网友评论

          本文标题:php 读取文件某一行数据

          本文链接:https://www.haomeiwen.com/subject/okxnwqtx.html