Page 1 of 1

XML/RSS Parse

Posted: Mon Aug 20, 2007 9:52 am
by lj2007
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


I have the following script to parse an XML/RSS feed. What i want to do is to have three random items from the feed show up  - however on some refreshes I am getting duplicate items showing up - is there a simple way to eliminate duplicates??

Thanks!!

Code: Select all

<?php
							
							define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
							define('MAGPIE_DIR', 'magpie/');
							
							require_once(MAGPIE_DIR.'rss_fetch.inc');
							
							if ( isset($_GET['url']) ) {
								$url = $_GET['url'];
							}
							else {
								$url = 'http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/front_page/rss.xml';
							}
							
							
							$rss = fetch_rss( $url );
//Change the number to change the number of items shown							
$count = 3;

for ($i = 0; $i < $count; $i++)

{$items2[] = $rss->items[rand(0, count($rss->items)-1)];}

if ($rss) {

foreach ($items2 as $item) {
$href = $item['link'];
$title = $item['title'];
$description = $item['description'];
echo "<p class='dark'>> <b><a class='dark' href=$href>$title</a></b><br />$description</p>";
} 								
							}
else {
echo "Error: " . magpie_error();
}
?>


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Mon Aug 20, 2007 2:20 pm
by superdezign
You eliminate duplicates by checking if the entry was already used before using it. in_array() or [url=http:/php.net/array-key-exists]array_key_exists[/url] could be of use, depending on which part of the array is copied.

Posted: Mon Aug 20, 2007 2:33 pm
by volka
http://de2.php.net/array_rand might be of interest.

Code: Select all

$rss = fetch_rss( $url );

$selected_items = array_rand($rss->items, 3);
foreach( $selected_items as $key ) { 
  $item = $rss->items[$key];
  echo '<p class="dark"><a class="dark" href="', $item['href'], '">', $item['title'], '</a><br />', $item['description'], "</p>\n";
}
(untested)