读取文件内容

/**
     * 读取文件特定行
     * @param type $filename
     * @param type $startLine
     * @param type $endLine
     * @param type $method
     * @return array
     */
    protected function getFileLines($filename, $startLine = 1, $endLine = 50, $method = 'rb') {
        $content = array();
        $count = $endLine - $startLine;
        $fp = fopen($filename, $method);
        if (!$fp)
            return $content;
        for ($i = 1; $i < $startLine; ++$i) {// 跳过前$startLine行
            fgets($fp);
        }
        for ($i = $startLine; $i <= $endLine; ++$i) {
            $content[] = fgets($fp); // 读取文件行内容
        }
        fclose($fp);
        $content = array_filter($content);  // array_filter过滤:false,null,''
        foreach ($content as $key => $value) {
            $content[$key] = json_decode($value, true);
        }
        return $content;
    }

    /**
     * 获取文件有多少行
     * @param type $file
     * @return type
     */
    protected function count_line($file) {
        $fp = fopen($file, "r");
        $i = 0;
        while (!feof($fp)) {
            //每次读取2M
            if ($data = fread($fp, 1024 * 1024 * 2)) {
                //计算读取到的行数
                $num = substr_count($data, "\n");
                $i+=$num;
            }
        }
        fclose($fp);
        return $i;
    }

 

posted on 2017-04-06 19:11  bandbandme  阅读(132)  评论(0编辑  收藏  举报