开发者

Randomize external RSS feed order in PHP

I'm using a third-party AJAX slideshow for a website that ta开发者_JS百科kes 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.


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);


Here is a full example of what worked for me. The two first answers didn't work for some reason in my case. This one is very similar to the second one.

<?php 
header("Content-Type: text/xml");

if (isset($_GET["rss"])) {
    $url = $_GET["rss"];
    randomizeAndDumpRss($url);
}

function randomizeAndDumpRss($url) {
    $dom = new DOMDocument;
    $dom->load($url);
    $channel = $dom->getElementsByTagName('channel')[0];
    $items = $channel->getElementsByTagName('item');

    $allitems = array();
    foreach ($items as $item) {
        $allitems[] = $item;
    }

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

    shuffle($allitems);

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

    print $dom->saveXML();
}
?> 

Simply use this php with ?rss=rss_url_to_randomize.


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();

}


> <?php
$random = rand();
$url = "http://www.gaafilaa.com/index.php/shop/feed/?orderby=rand" . "&v=$random";
$rss = simplexml_load_file($url);
if($rss)
{
  $items = $rss->channel->item;
  foreach($items as $item)
  {
    $title = $item->title;
    $link = $item->link;
    $image = $item->product->image;
    echo '<a href="'.$link.'" target="_blank">'.$title.'</a></br>';
    echo '<a href="'.$link.'" target="_blank"><img src="'.$image.'" style="width:100%;"/img></a></br>';
    echo '............................................</br>';
  }
}
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜