php 定时更换网页内容,简单的PHP伪缓存并定时抓取某页面内容

原文:http://www.nowamagic.net/librarys/veda/detail/904

需求:要抓取某个页面的一部分内容,然后iframe到别的页面去。iframe的时候,不需求每次都访问源页面,而是每天只读取源页面一次,并生成文件,iframe的时候只访问该暂时文件,也就是伪缓存啦。这么做适合访问量不大的页面,降低数据库访问压力。

程序设计如下:

function get_page_content()

{

$url = "http://www.nowamagic.net/";

$contents = file_get_contents($url);

//如果出现中文乱码使用下面代码

//$getcontent = iconv("gb2312″, "utf-8″,$contents);

//echo $contents;

//$pos = strstr($contents, '

');

//print_r($pos);

$array = explode('

', $contents);

$htmlarray = explode('

', $array[0]); // HTML部分

$cssarray = explode('

', $htmlarray[0]);

$css_rem_inner = explode('', $cssarray[0]);

$css_min = explode('

$str_css = $css_min[0];

$head = ' ';

$str_1 = '

';

$str_html = $htmlarray[1];

$content = $str_css.$head.$str_1.$str_html;

return $content;

}

$cache_file = "tmp.html";

$cache_time = 60*60*24;

/**

ob_start();

echo $content;

file_put_contents($cacheFile,ob_get_contents());

ob_end_flush();

**/

echo date("Y-m-d H:i:s", time());

echo '
';

echo date("Y-m-d H:i:s", floor(@filemtime($cache_file)));

if(time() - $cache_time > floor(@filemtime($cache_file)) )

{

$content = get_page_content();

file_put_contents($cacheFile, $content);

header('Location: http://www.nowamagic.net/tmp.html');

}

else

{

header('Location: http://www.nowamagic.net/tmp.html');

}

?>

解释下:

$cache_time = 60*60*24; 缓存时间为一天。

if(time() - $cache_time > floor(@filemtime($cache_file)) ) 如果当前时间减去一天大于暂时文件的修改时间。

$content = get_page_content(); 就读取页面内容并重新生成暂时文件。

就这么简单。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值