You are here:  » Random Selection from XML Feed


Random Selection from XML Feed

Submitted by JasonG on Mon, 2007-01-15 14:15 in

Hi David,

Is there a way of retrieving a random number of items from an XML feed?

(i.e. I would like to be able to randomly select 5 items from a feed to display as featured items)

I don't have an example feed at present so if you need more info please let me know.

Kind regards

Jason

Submitted by support on Mon, 2007-01-15 14:21

Hi Jason,

The only issue with selecting random records is the fact that you don't know in advance how many records there are in total.

This means that you have no option really but to load all records into memory (into an array); and then select random items to display from the array after all records have been parsed.

It's quite easy to do; you just have to be aware of the memory constraints if you are working with a large feed. Here's an example of this method:

<?php
  
// global array to hold all records
  
$records = array();
  function 
myRecordHandler($record)
  {
    
// add this record to the global array
    
global $records;
    
$records[] = $record;
  }
  
// parse the feed to load all records
  
MagicParser_parse("feed.xml","myRecordHandler");
  
// use PHPs array_rand function to extract n random records
  
$random array_rand($records,5);
  foreach(
$random as $record)
  {
    
// display $record here just as in myRecordHandler
  
}
?>

Hope this helps,
Cheers,
David.

Submitted by JasonG on Mon, 2007-01-15 15:48

Fantastic.

Many thanks as always David.

Kind regards

Jason

Submitted by JasonG on Thu, 2007-01-18 11:50

Hi David,

Sorry to bother you again on this but I can't seem to get it to work.

If I put code in the myRecordHandler to display fields it works fine but if I put it within the foreach loop after $random is set, nothing displays?

Within the foreach loop I'm putting echo $record["NAME"].';

Kind regards

Jason

Submitted by support on Thu, 2007-01-18 12:02

Hi Jason,

Sorry - my fault for not checking how array_rand() works carefully enough. It only returns index numbers, not actual array values - so a small modification is required to make this work...!

<?php
  
// global array to hold all records
  
$records = array();
  function 
myRecordHandler($record)
  {
    
// add this record to the global array
    
global $records;
    
$records[] = $record;
  }
  
// parse the feed to load all records
  
MagicParser_parse("feed.xml","myRecordHandler");
  
// use PHPs array_rand function to extract n random records
  
$random array_rand($records,5);
  foreach(
$random as $i)
  {
    
$record $records[$i];
    
// display $record here just as in myRecordHandler
  
}
?>

The change is just at the end there; using $i in the foreach loop; and then using that value to select a $record from the $records array...

Cheers,
David.

Submitted by JasonG on Thu, 2007-01-18 12:13

Excellent, now working a treat :)

Cheers David