PHP和AJAX:缓存RSS数据


PHP and AJAX: cache RSS data

考虑以下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文件如下:

$urlD = "someurl";
    $xmlD = simplexml_load_file($urlD);
    $itemD = $xmlD->channel->item;

我需要缓存$itemD$xmlD对象-不确定哪一个。这应该缓存1小时,然后再次从url。对于代码缓存的任何帮助都将非常感激。

看一下这个函数:

    <?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);