Reputation: 1
I've been trying to randomize the order in which the rss feed of my website outputsthe items, but without any luck yet. This is the part of the code which creates the actual xml.
class RSSFeed {
private $items;
public function __construct() {
$this->items = array(); }
public function addItem($item) {
$this->items[] = $item;}
public function dumpXML() {
echo '<?xml version="1.0" encoding="UTF-8"?>', PHP_EOL;
echo '<rss version="2.0">', PHP_EOL;
echo '<channel>', PHP_EOL;
foreach ($this->items as $item) {
echo '<item>', PHP_EOL;
echo '<title><![CDATA[', $item['title'], ']]></title>', PHP_EOL;
echo '<link>', $item['link'], '</link>', PHP_EOL;
echo '<guid>', $item['link'], '</guid>', PHP_EOL;
echo $item['description'], ']]>';
echo '</description>', PHP_EOL;
echo '</item>', PHP_EOL;
}
echo '</channel>', PHP_EOL;
echo '</rss>', PHP_EOL;
I've tried using shuffle($items), but the feed stops working. I also tried creating a new array with the same items and shuffle that, but the result was the same. Who can help me? It's been so long since i've written some code that i've forgotten important stuff...
Upvotes: 0
Views: 1230
Reputation: 197757
You do not need to shuffle the array itself, only the order of the items:
$keys = array_keys($this->items);
shuffle($keys);
foreach ($keys as $key) {
$item = $this->items[$key];
...
}
See the array_keys
Docs and shuffle
Docs functions.
To further improve, create a function that outputs the array as is:
...
private function echoRSS(array $items) {
echo '<?xml version="1.0" encoding="UTF-8"?>', PHP_EOL;
echo '<rss version="2.0">', PHP_EOL;
echo '<channel>', PHP_EOL;
foreach ($items as $item) {
...
}
...
You can then easier do whatever you want, e.g. by calling that function then:
public function dumpXML() {
$items = $this->items;
shuffle($items);
$this->echoRSS($items);
}
Hope this is helpful.
Upvotes: 0
Reputation: 324630
Before outputting the results, you can do one of two things:
shuffle($this->items);
This destroys the original order of the items. If that order has some importance, try this:
$tmp = $this->items;
shuffle($tmp);
foreach($tmp...
Upvotes: 3