php简单分页类
php简单分页类,方便演示,采用文件存放文章内容,用于php读取。
代码如下:
<?php class Page{ private $file;//文件内容 private $current;//当前页 private $totalPage;//总的页数 private $url;//url地址 private $pageLen;//每页显示的内容长度 function __construct($file,$len=500){ $this->file = file_get_contents($file); $this->current=isset($_GET['page'])?$_GET['page']:1; $this->pageLen = $len; $this->totalPage = $this->getTotalPage(); $this->url= $this->getUrl(); } //获取文件内容显示总共有多少页 private function getTotalPage(){ return ceil(strlen($this->file)/$this->pageLen); } //获得并分离url private function getUrl(){ $url =parse_url($_SERVER['REQUEST_URI']); parse_str($url['query'],$queryArr); unset($queryArr['page']); $queryStr = http_build_query($queryArr); return $url['path'].'?'.$queryStr.'&page='; } //首页 private function first(){ if($this->current>1)return "<a href='".$this->url."1'>首页</a>"; } //上一页 private function pre(){ if($this->current>1)return "<a href='".$this->url.($this->current-1)."'>上一页</a>"; } //下一页 private function next(){ if($this->current<$this->totalPage)return "<a href='".$this->url.($this->current+1)."'>下一页</a>"; } //末页 private function end(){ if($this->current<$this->totalPage) return "<a href='".$this->url.$this->totalPage."'>末页</a>"; } //分页列表 private function pager(){ for ($i=1;$i<=$this->totalPage;$i++){ if($i==$this->current){ $pageListStr.="<span style='font-size:20px;color:#f00'>".$i."</span> "; }else{ $pageListStr.="<a href='".$this->url.$i."'>".$i." </a>"; } } return $pageListStr; } //分页样式(显示方式,具体效果用css实现) public function pagerStyle($style=1){ switch ($style){ case 1: return "共有".$this->totalPage."页".$this->first().$this->pre().$this->pager().$this->next().$this->end(); break; case 2; return $this->pager(); break; } } //获取分页内容 public function getContents(){ $prePageLen = strlen($this->subStrs($this->current-1)); $currentPageLen = strlen($this->subStrs($this->current)); return substr($this->file, $prePageLen,$currentPageLen-$prePageLen); } //截取文件内容 private function subStrs($page){ $len= $page*$this->pageLen; for ($i = 0; $i < $len; $i++) { if(ord(substr($this->file,$i,1))>0xa0){//判断内容是否为中文字符,以防乱码 $string.=substr($this->file,$i,2); $i++; }else{ $string.=substr($this->file,$i,1); } } return $string; } } $php = new Page('luojing.txt',1000);//实例化一个分页类对象 echo "<div style='font-size:14px;line-height:1.8em;color:#666;padding:6px;width:960px;height:450px;'>".$php->getContents()."</div>"; echo "<div style='border:solid 1px #ccc;font-size:14px;color:#333'>"; echo $php->pagerStyle(); echo "</div>"; ?>