简体   繁体   中英

How to cache RSS feed data to display on website?

I am developing a website that will display the most recent item from a RSS feed. However, each time a user accesses the website, I'd like for the page to display cached data. This will make the page display much quicker since I plan on caching 50+ RSS feeds.

My question is, how do I cache an RSS feed, but make sure it updates in the background every 4 hours or so?

Thanks in advance.

Create a cache folder to store all the RSS feeds.

When the page is loaded, check to see if the file exists, if it doesn't download it and process it.

If the file exists and the result of filemtime($cached_file) + (60 * 60 * 4) is greater than time() , it means that it has been less than the 4 hours since the RSS feed was fetched. Display the page like normal. If that is not the case, redownload the file and display it.

There are many tutorials about for parsing RSS feeds in PHP. I prefer using PHP's DOM extension, but there are so many different ways you can do it.

I created a simple PHP class to tackle this issue. Since I'm dealing with a variety of sources, it can handle whatever you throw at it (xml, json, etc). You give it a local filename (for storage purposes), the external feed, and an expires time. It begins by checking for the local file. If it exists and hasn't expired, it returns the contents. If it has expired, it attempts to grab the remote file. If there's an issue with the remote file, it will fall-back to the cached file.

Blog post here: http://weedygarden.net/2012/04/simple-feed-caching-with-php/

Code here: https://github.com/erunyon/FeedCache

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM