Lately I have had "caching" on the brain and have been working on a decent way of caching.
So far I have found that caching is obviously faster and in XML format makes it really easy to iterate through in Object format.
My methods so far are
- Checking a database table for current cached item information.
- If it has an expiration date or does not exist the feed needs to be cached.
- If needs to be cached - Caching will grab the feed via curl, fopen, or file_get_contents()
- Feed will then be stored in a file in a specific directory on the server.
- Database will either be updated or inserted with feed information.
Right now I am thinking about having a hybrid method here that will come up with a way to setup expirations inside of the "feed." But I still like having information in the database as then I can loop through old archived feed information if I want to.
The functions I am using goes as follows:
- MySQL Query to check database for cached item. Creating a couple different unique identifiers such as URL, location, etc...
- PHP function "SimpleXMLElement"
Function basically makes an xml string and converts it to an object format.
Iterating is as easy as doing the following:
$xml = new SimpleXMLElement($cached);
if(is_object($xml))
foreach($xml->channel->item as $k=>$v){
echo $v->title;
}
The above I use on either the new cached item or the old stored feed. Typically my caching time varies. For something like a twitter feed I cache for about 2 hours. On other feeds I have no expiration set as they should be recached "manually" For instance recently I made a section in my CMS to check Facebook stats on likes, recommends, clicks etc... These are queries that query the facebook open graph and returns an XML feed. I store this feed in my cache and setup an ajax call to a page that pulls these feeds and updates the page.
Something like this is best to not pull every single time a page loads but rather every so often.