考虑以下AJAX调用来加载点击事件的RSS新闻数据:
$(function() {
$(document).ready(function() {
$('.msg_head').eq(0).click(function(){
$('.msg_body').eq(0).load('printSideNews.php');
$('.loadMessage').eq(2).hide();
});
});
});
printSideNews.php
看起来像这样:
include ('newsFeed.php');
function printNewsMenu($itemD){
for ($i = 0; $i < 4; $i++) {
if($itemD==null)
echo "An error has occured, please try again later";
$article_title = $itemD[$i]->title;
$article_link = $itemD[$i]->link;
echo "<a href='".$article_link."' title='".$article_title."' target='_blank'>". $article_title. " </a></br>". PHP_EOL;
}
printNewsMenu($itemD);
包含的newsFeed.php
文件lloks如:
$urlD = "someurl";
$xmlD = simplexml_load_file($urlD);
$itemD = $xmlD->channel->item;
我需要缓存$itemD
或$xmlD
对象 - 不知道哪一个。这应缓存1小时,然后再从网址中获取。任何有关代码缓存此混乱的帮助都将非常感激。
答案 0 :(得分:1)
看看这个功能:
<?php
function cacheObject($url,$name,$age = 86400)
{
// directory in which to store cached files
$cacheDir = "cache/";
// cache filename constructed from MD5 hash of URL
$filename = $cacheDir.$name;
// default to fetch the file
$cache = true;
// but if the file exists, don't fetch if it is recent enough
if (file_exists($filename))
{
$cache = (filemtime($filename) < (time()-$age));
}
// fetch the file if required
if ($cache)
{
$xmlD = simplexml_load_file($url);
$itemD = $xmlD->channel->item;
file_put_contents($filename,serialize($itemD));
// update timestamp to now
touch($filename);
}
// return the cache filename
return unserialize(file_get_contents($filename));
}
$urlD = "someurl";
$itemD = cacheObject($urlD,'cacheobject',3600);