2011-10-12 57 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