andybeak
10/3/2016 - 1:29 PM

Very simple zero feature rss read class

Very simple zero feature rss read class

class RSS
{

    const CACHE_FILENAME = 'feed.cache';

    const CACHE_TTL = 60;

    /**
     * Public exposed function to read the feed, checks if the cache needs to be refreshed and if so reads from web,
     * otherwise reads from the cache
     * @static
     * @access public
     *
     * @param $url
     *
     * @return \SimpleXMLElement
     */
    public static function readFeed($url)
    {
        if (file_exists(self::CACHE_FILENAME) && ((time() - filemtime(self::CACHE_FILENAME)) < self::CACHE_TTL)) {

            $simpleObject = self::readFromCache($url);

        } else {

            $simpleObject = self::readFromWeb($url);

        }

        return $simpleObject;

    }

    /**
     * Reads the file from the locally stored cache
     * @static
     * @access public
     * @return \SimpleXMLElement
     */
    private static function readFromCache()
    {
        return simplexml_load_file(self::CACHE_FILENAME);
    }

    /**
     * Reads the xml from the published web url
     * @static
     * @access public
     *
     * @param $url
     *
     * @return \SimpleXMLElement
     */
    private static function readFromWeb($url)
    {
        $feedContents = file_get_contents($url);

        file_put_contents(self::CACHE_FILENAME, $feedContents);

        return self::readFromCache();
    }

}