搜尋
首頁php教程php手册简单的PHP伪缓存并定时抓取某页面内容

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

程序设计如下:

<?php
function get_page_content()
{
	$url = "http://www.bkjia.com/";
	$contents = file_get_contents($url);
	//如果出现中文乱码使用下面代码
	//$getcontent = iconv("gb2312″, "utf-8″,$contents);
	//echo $contents;
	//$pos = strstr($contents, '<div class="hot_news">');
	//print_r($pos);
	$array = explode('<div class="hot_news">', $contents);
	$htmlarray = explode('<div class="car_tab border4">', $array[0]); // HTML部分
	$cssarray = explode('<div class="hometop">', $htmlarray[0]);
	$css_rem_inner = explode('<!--[if !IE]>导航<![endif]-->', $cssarray[0]);
	$css_min = explode('<script type="text/javascript" src="http://www.bkjia.com/ad_comm_t.js">', $css_rem_inner[0]);
	$str_css = $css_min[0];
	$head = '<base target="_blank"></base></head> ';
	$str_1 = '<div class="car_tab border4">';
	$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 '<br />';
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.bkjia.com/tmp.html');
}
else
{
	header('Location: http://www.bkjia.com/tmp.html');
}
?>

解释下:

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

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

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

就这么简单。

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具