in Uncategorised

How to cache external custom JSON data within Magento

I thought I’d share a quick and simple method to improving loading times when extracting JSON data from an API within a Magento build.

For one particular client, this improved loading times considerably and in some cases by over two seconds.

$cache_key = 'json_feed_name';
$cache_tag = 'homepage';
if ( false !== ($list = Mage::app()->getCache()->load($cache_key)) ) {
    $list = unserialize($list);
} else {
    $json = file_get_contents($_SERVER['HTTP_X_FORWARDED_PROTO'].'://'.$_SERVER['HTTP_HOST'].'/api/?json=get_content_feed');
    $list = json_decode($json);
    Mage::app()->getCache()->save(serialize($list), $cache_key, array($cache_tag), 3600*6);

Please note, I’ve used $_SERVER['HTTP_X_FORWARDED_PROTO'] to get the protocol used by CloudFlare as the service we’re contacting uses their service.

Write a Comment