You are here:  » Display random items from RSS Feed?

Support Forum



Display random items from RSS Feed?

Submitted by atlanta1 on Tue, 2008-12-23 11:54 in

I'm using the code below to display a maximum of 16 items in 4 columns from "my own" rss feed.

My feed contains 30+ items.

Is there a way to modify the code so the page displays 16 random items from my feed - not just the first 16?

Thanks in advance!

<?php
  
require("MagicParser.php");
  
$ItemMax 16;
  
$ItemCount 0;
  
$columns 4;
  
$current_column 0;
  function 
myRecordHandler($item)
  {
    global 
$ItemMax;
    global 
$ItemCount;
    global 
$columns;
    global 
$current_column;
    print 
"<td style='font-size:11px;' align='left' valign='top' width='220'>";
    print 
"<h2><a href='".$item["LINK"]."' target='_blank'>".$item["TITLE"]."</a></h2>";
    print 
$item["DESCRIPTION"];
    print 
"</td>";
    
$current_column++;
    if (
$current_column == $columns)
    {
      print 
"</tr><tr>";
      
$current_column 0;
    }
    
$ItemCount++;
    if (
$ItemCount==$ItemMax) return TRUE;
  }
  {
    
$url 'http://www.domainname.co.uk/rss-feed.rss';
 
// start the table
    
print "<table cellpadding='10' width='748'>";
    print 
"<tr>";
    
// parse the URL to generate each result in a table cell (myRecordHandler does this)
    
MagicParser_parse($url,"myRecordHandler","xml|RSS/CHANNEL/ITEM/");
    
// end the table
    
print "</tr>";
    print 
"</table>";
  }
?>

Submitted by support on Tue, 2008-12-23 12:43

Hi,

Try something like this:

<?php
  
require("MagicParser.php");
  
$ItemMax 16;
  
$ItemCount 0;
  
$columns 4;
  
$current_column 0;
  
$items = array();
  function 
myRecordHandler($item)
  {
    global 
$items;
    
$items[] = $item;
  }
  
$url 'http://www.domainname.co.uk/rss-feed.rss';
  
// start the table
  
print "<table cellpadding='10' width='748'>";
  print 
"<tr>";
  
// parse the URL to generate each result in a table cell (myRecordHandler does this)
  
MagicParser_parse($url,"myRecordHandler","xml|RSS/CHANNEL/ITEM/");
  
shuffle($items);
  foreach(
$items as $item)
  {
    print 
"<td style='font-size:11px;' align='left' valign='top' width='220'>";
    print 
"<h2><a href='".$item["LINK"]."' target='_blank'>".$item["TITLE"]."</a></h2>";
    print 
$item["DESCRIPTION"];
    print 
"</td>";
    
$current_column++;
    if (
$current_column == $columns)
    {
      print 
"</tr><tr>";
      
$current_column 0;
    }
    
$ItemCount++;
    if (
$ItemCount==$ItemMax) break;
  }
  
// end the table
  
print "</tr>";
  print 
"</table>";
?>

Instead of displaying the output within myRecordHandler, this version loads all records into an array ($items) then shuffles the array; then displays the first $ItemMax records as part of the foreach loop...

Hope this helps!

Cheers,
David.