I wanted to create a simple RSS reader for myself. All I wanted to see was some top headline from top news site (according to Google it’s BBC, CNN and Fox News). No images, no fluff, just a headline and a link. I settled on 7 headline, which provided me a good balance between too much and too little data.
You can check it out at https://techtldr.com/eznews/.
My first intent was to just use JavaScript, however, I run into an issue with RSS feeds preventing cross-origin HTTP request (CORS).
I then decided to use a back end technology of sorts.
Even though I love Python and Node, they are both not very easy to deploy. I wanted something quick that I can deploy on my own server. Since I am already running WordPress , it was VERY easy to create a simple PHP script.
All I had to do is:
- Create a folder
- Add a simple PHP file. You can see my implementation here: https://github.com/akras14/eznews
It works great. Mobile Friendly. Blazing fast. No large JavaScript files to download.
Here is the core functionality:
function getFreshContent() {
$html = "";
$newsSource = array(
array(
"title" => "BBC",
"url" => "http://feeds.bbci.co.uk/news/world/rss.xml"
),
array(
"title" => "CNN",
"url" => "http://rss.cnn.com/rss/cnn_latest.rss"
),
array(
"title" => "Fox News",
"url" => "http://feeds.foxnews.com/foxnews/latest"
)
);
function getFeed($url){
$rss = simplexml_load_file($url);
$count = 0;
$html .= '<ul>';
foreach($rss->channel->item as$item) {
$count++;
if($count > 7){
break;
}
$html .= '<li><a href="'.htmlspecialchars($item->link).'">'.htmlspecialchars($item->title).'</a></li>';
}
$html .= '</ul>';
return $html;
}
foreach($newsSource as $source) {
$html .= '<h2>'.$source["title"].'</h2>';
$html .= getFeed($source["url"]);
}
return $html;
}
Code language: PHP (php)
I’ve added Bootstrap via CDN to make it look prettier, and since it is coming from CDN, it has a minor performance hit.
The only issue with PHP, is that it did not offer an easy way to cache data between various requests. Forcing me to hit RSS feed every time I wanted to render the page. This would be fine, if I was the only one consuming that page, but since I was planning to host it live on the internet, I wanted to come up with a more robust solution.
Luckily, David Walsh came up with a simple solution allowing me to cache my RSS request in a file. I am caching my requests for 5 minutes, meaning I will hit RSS urls at most 12 times per hour.
So there you have it, a simple RSS reader in 85 lines of PHP.