<?php
class pan{
private $cacheFold='cache/';//缓存目录
private $cacheTime=600;//缓存时间,单位秒,为0时不使用缓存
private $url="http://";//搜索引擎接口
public $from='';//分辨来自缓存还是实时获取
function getResult($k,$p)//实例返回结果的方法
{
$k=trim($k);
if($k=='')
{
return 0;
}
$p=intval($p);
$p=($p<1)?1:$p;
$p=($p>100)?100:$p;
$result=0;
//$cache=$this->existCache($k,$p);
if(($this->cacheTime)!=0 && ($cache=$this->existCache($k,$p))!='1')
{
if($this->outCacheTime($cache))
{
unlink($cache);
$result=$this->getFromUrl($k,$p);
$this->from='缓存超时而实时获取';
}
else{
$result=$this->getFromCache($cache);
$this->from='来自缓存';
}
}
else{
$result=$this->getFromUrl($k,$p);
$this->from='实时获取';
}
return $result;
}
function existCache($k,$p)
{
$k=md5($k);
$str="{$this->cacheFold}{$k}#{$p}#*.txt";
$r=glob($str);
//print_r($r);
$n=count($r);
//echo $n;
if($n && $r[0]!='')
{
return $r[0];
}
else{
return '1';
}
}
function outCacheTime($cache)//判断是否超时
{
$now=time();
$tmp=basename($cache);
$tmp=explode('#',$tmp);
$tmp=explode('.',$tmp[2]);
$tmp=$tmp[0];//文件中的时间戳
if(($now-$tmp)>$this->cacheTime)
{
return 1;
}
else{
return 0;
}
}
function getFromUrl($k,$p)
{
$con=$this->getPage($k,$p);
$result=$this->jiexi($con);
if($this->cacheTime!=0 && $con!='')
{
$this->saveCache($k,$p,$result);
}
return $result;
}
function saveCache($k,$p,$result)
{
$now=time();
$k=md5($k);
$con='';
$str="{$this->cacheFold}{$k}#{$p}#{$now}.txt";
for($i=0;isset($result[$i]);++$i)
{
$con="$con".urlencode($result[$i][0]).'#'.urlencode($result[$i][1]).'#'.urlencode($result[$i][2])."\n";
}
file_put_contents($str,$con);
}
function getPage($k,$p)//获取页面
{
$k="{$k} site:pan.baidu.com";
$k=urlencode($k);
$url="
http://m.sm.cn/s?q={$k}&page={$p}";
return
@file_get_contents($url);
}
function jiexi($c)//页面内容解析为数组
{
preg_match_all("~<div\ class=\"article.*</div></div>~Uis",$c,$c);
$c=$c[0];
$result=array();
for($i=0;isset($c[$i]);++$i)
{
$c2=$c[$i];
preg_match("~<a\ href=\"(.*)\">.*</a>~Uis",$c2,$c3);
$con[0]=str_replace('&','&',$c3[1]);
$con[1]=strip_tags($c3[0]);
preg_match("~<p>.*</p>~Uis",$c2,$c3);
$con[2]=strip_tags($c3[0]);
$result[$i]=$con;
}
return $result;
}
function getFromCache($cache)
{
$result=array();
$con=file($cache);
for($i=0;isset($con[$i]);++$i)
{
$c=trim($con[$i]);
$c=explode('#',$c);
$c[0]=urldecode($c[0]);
$c[1]=urldecode($c[1]);
$c[2]=urldecode($c[2]);
$result[$i]=$c;
}
return $result;
}
}
?>