2011-10-12 61 views
0

考虑下面的AJAX调用加载上单击事件RSS新闻数据:PHP和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这样的:我需要缓存$itemD$xmlD对象 - 不确定哪一个。这应该被缓存1小时,然后再从url中获取。任何帮助代码缓存这个混乱将不胜感激。

+0

什么是你的** **的问题和你尝试过什么迄今为止解决问题了吗?这不是租赁编码器,而是支付0的帮助,所以除非你澄清你所尝试过的以及你失败的地方 - 你错了。 –

+0

你有任何会话状态的用户? –

+0

我不会构建用户功能。该网站将只有访问者。这个想法是有一些文件夹缓存不使用会话。 – George

回答

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); 
+0

现在我在XAMPP服务器上使用本地主机,所以不需要URL? – George

+1

已将您的代码更新为示例,使您的** newsFeed.php **看起来像,用1小时缓存您的Feed –

+0

真的很有用,现在我试着实现它 – George