XML/RSS Parse

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lj2007
Forum Newbie
Posts: 1
Joined: Mon Aug 20, 2007 9:49 am

XML/RSS Parse

Post 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]
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post 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.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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)
Post Reply