I write this class to process and output xml/rss feeds. I'm still working on, but any suggestion will be appreciated. As a little trick if the xml file come from an online resource, I've added a method to cache the xml file as a json file.
<?php
class NewsFeed{
public $url;
private $cachedFeed;
private $cachedFile;
private $feed;
private $xml;
private $json;
public function __construct($url){
$this->url = $url;
}
public function showLiveFeed(){
$feed = $this->processFeed();
return json_decode($feed, true);
}
public function showCachedFeed(){
$cachedFeed = $this->loadCachedFile();
return json_decode($cachedFeed, true);
}
private function processFeed(){
$feed = $this->url;
$xml = simplexml_load_file($feed, 'SimpleXMLElement', LIBXML_NOCDATA);
$json = json_encode($xml);
$cacheFeed = file_put_contents('cachedFeed.json', $json);
return $json;
}
private function loadCachedFile(){
if(file_exists('cachedFeed.json')){
$cachedFile = file_get_contents('cachedFeed.json');
return $cachedFile;
}
}
}
?>