RSS Feed Caching


/ Published in: PHP
Save to your folder(s)

Note: This also uses a flat file to cache the results, be sure to also upload the 'rss_cache.txt' file.

Usage:


Copy this code and paste it in your HTML
  1. function get_news($url=''){
  2.  
  3. //save the rss file cache
  4. $validCache = false;
  5. if (file_exists('rss_cache.txt')) {
  6. $contents = file_get_contents('rss_cache.txt');
  7. $data = unserialize($contents);
  8. if (time() - $data['created'] < 24 * 60 * 60) {
  9. $validCache = true;
  10. $feed = $data['feed'];
  11. }
  12. }
  13.  
  14. if (!$validCache) {
  15.  
  16. $feed = file_get_contents($url);
  17. $data = array ('feed' => $feed, 'time' => time() );
  18. file_put_contents('rss_cache.txt', serialize($data));
  19. }
  20.  
  21. //get the xml object
  22. $news = new SimpleXMLElement(trim($feed));
  23.  
  24. $result = array();
  25. foreach($news->channel->item as $item){
  26. $result[] = array(
  27. 'title' => $item->title,
  28. 'link' => $item->link,
  29. 'description' => trim($item->description)
  30. );
  31. }
  32. return $result;
  33.  
  34. }
  35. function display_news($news, $limit=3){
  36.  
  37. print "<ul class='news-feed'>";
  38. $cnt = 0;
  39. foreach($news as $n){
  40. if($cnt == $limit) return;
  41. print '<li class="news-item"><a href="' . $n['link'][0] . '" target="_blank">' . $n['title'][0] . '</a><p>';
  42. print $n['description'] . ' <a href="' . $n['link'][0] . '" target="_blank"><strong>read more</strong> &raquo;</a>';
  43. print '</li>';
  44. $cnt++;
  45. }
  46.  
  47. print '</ul>';
  48.  
  49. }

URL: http://stackoverflow.com/questions/6176561/caching-a-wordpress-rss-feed-with-php

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.