views:

175

answers:

2

I'm using a third-party AJAX slideshow for a website that takes an RSS feed as its picture source. I would like to randomize the order of the pictures, but that's not a feature of the slideshow (or the RSS feed I'm pulling from).

Surely it shouldn't be difficult to write a short function in PHP that takes an external RSS feed, randomizes the items and re-publishes the same feed 'out of order'. I just can't seem to make it work.

+2  A: 

Are you using DOM XML? Then just shuffle the array on import.

$xml = new DOMDocument();
$articles = $xml->getElementsByTagName("article");
$data = array();
foreach ($articles as $article) {
    data[] = ...
}
shuffle($data);
Radek
By the way, unlike fetching data from a database, parsing XML (RSS) is intensive.
Radek
getElementsByTagName() returns an object, not an array, and can't be shuffled.
Mr. Brent
you are right, have updated slightly so that you save your data into an array() from nodes first, then shuffle :)
Radek
Perfect, thanks.
Mr. Brent
A: 

What worked:

$dom = new DOMDocument;
$dom->load($url);

// Load the <channel> element for this particular feed
$channel = $dom->documentElement->firstChild;

$items = $channel->getElementsByTagName('item');

// duplicate $items as $allitems, since you can't remove child nodes
// as you iterate over a DOMNodeList
$allitems = array();
foreach ($items as $item) {
 $allitems[] = $item;
 }

// Remove, shuffle, append
foreach ($allitems as $item) {
 $channel->removeChild($item);
}

shuffle($allitems);

foreach ($allitems as $item) {
 $channel->appendChild($item);
 }

print $dom->saveXML();

}

Mr. Brent
This is a nice tip. I was working on some apps that will use this sort of feature and coming across it here will definitely make my work a lot easier.
Helen Neely