RSS news feed in widget, with complete PHP source code

Do you want to display news on your classifieds website? Display local news, industry news related to your classifieds website, latest blog posts if you have blog related to your website, twitter feed converted to RSS with external service like or similar services. Any standard RSS feed will work.

RSS news widget, PHP source code

This snippet will extract news from several RSS sources and display latest news in widget. Classibase widgets can render PHP code. In this tutorial, with complete source code, you will learn how to display RSS news in widget.


  • Read multiple RSS feeds - You can display combined feed using several RSS sources.
  • Load data using ajax for not blocking and slowing regular page generation.  - Sometimes loading external RSS data may take up to 5-10 seconds time. Loading feed with ajax will make your site load faster and add news widget after page fully loaded.
  • Caching loaded results. This will prevent loading RSS from source on every page request. Instead widget will cache results. Cached results will be displayed much faster.
  • Load one source at a time. If you defined several sources loading all of them at once may slow down your website. If you have 5 sources and each takes 5 seconds to load then if you load all at once it will take 25 seconds. In this widget we load one source at a time, other sources will be loaded with next page.
  • Open news in new window. You do not want your visitor to leave your site so news will open in new window when clicked.
  • Removes any URL from title text. Some RSS feeds have urls inside title which is not necessary to display. Because title will be linked to related article anyway.
  • Keep old result for short time if source is not available at time of request. This is useful if you do not want to display and cache empty result.
  • Timeout after 5 seconds if source RSS loads slowly due to slow network or error on source server. If not set the PHP default it is 60 seconds which is too much.
  • Sleep time 60 seconds between each new load from external source. This will prevent overloading server with simultaneous load requests.
  • Simultaneous source load prevention in case load requested by other client while RSS is being loaded by first request. Seconds request will show old cached result or empty result.


RSS news Widget Code Snippet


	//ini_set('display_errors', '1');
	Benchmark::cp('load rss:BEGIN');
	$max = 5;
	$cache_time = 5*3600;
	$cache_time_empty = 20*60;
	$cache_time_sleep = 60;

	$rss_src = array(
			"timeout" => 5,  //5 Seconds

	// load result from db 
	$result = Config::option('_widget_rss',null,true);
		$result = @unserialize($result);
		$result = array();
	/*$_result = array(
					['date from rss x']=>array(
						'title'=>'title text here',

	// remove deleted sources 
	$result_clone = $result;
	// get last result time for not loading xml consecutively
	$last_load_time = 0;
	foreach($result_clone as $k=>$v){
			$last_load_time = $v['time'];
			// remove from result and update db 
		// load one rss data if not found or expired in DB
		foreach($rss_src as $k=>$v){		
			// check if data exists 
			if(!isset($result[$k]) || $result[$k]['time']<REQUEST_TIME-$cache_time){
				// create placeholder record with low time for not overloading server with consecutive requests
				//  get this record from source					
				$result_items = array();
				Benchmark::cp('load rss:START');	
				$response = file_get_contents($v, false, stream_context_create($arrContextOptions));
				Benchmark::cp('load rss:'.$v);
					$xml = simplexml_load_string($response);
						$cnt = 0;
						foreach($xml->channel->item as $item){
							$date = $item->pubDate.'';	
							$date_time = strtotime($date);	
							// remove urml from title
							//$string = "The Third Culture: The Frontline of Global Thinking;via @edge";
							$regex = "@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@";
							$title = $item->title.'';
							$title = preg_replace($regex, ' ', $title);
							$title = trim($title," -");
				// if no items then keep time short 
				$time = REQUEST_TIME;
					$time -= $cache_time-$cache_time_empty;
						// keep old items 
						$result_items = $result[$k]['items'];
				// loaded from source then break here 

	// store result if required 

	// now format result as html 
	foreach($result as $k=>$v){
		foreach($v['items'] as $item_k=>$item_v){
	// order by key (date)
	foreach($_result as $item)
		$return.='<li><a href="'.View::escape($item['link']).'" target="_blank">'.View::escape($item['title']).'</a> <i>'.View::escape($item['date']).'</i></li>';
		$return = '<div id="_widget_rss"><ul>'.$return.'</ul></div>';
	echo $return;
	Benchmark::cp('load rss:END');
	//echo '<!-- '.Benchmark::report().'-->';
{	?>
	<div id="_widget_rss_"></div>
			// get #_widget_rss
			var $data = $(data);
				$data = $('#_widget_rss:first',$(data));


To add this widget follow these steps

  1. Update RSS sources defined in $rss_src array.
  2. Navigate to "Apperance" -> "Widgets" page in admin panel and add text widget to any sidebar that you want.
  3. Paste widget snippet to Text field. Add title to the widget.
  4. Select PHP from text format.
  5. Save widget.

Visit your website front end and navigate couple pages to fully load all RSS sources. News will be displayed in widget area. You can adjust  following variables in code:

  • $max = 5; Defines number of news items to be displayed in widget.
  • $cache_time = 5*3600; Defines cache time in seconds. News will be updated after this period of time.

If you have any questions or reviews please write in comments.

105 (+1) visits

Leave a Reply

Your email address will not be published. Required fields are marked *

  • Classifieds Business Newsletter

    Get discounts and tips about growing your classifieds website.