Combine 2 or more xml files, sort, dedup and display with php

Want to combine 2 or more xml/rss files with php? This commented code should get you started.

The 2 xml files will need to be structured the same in order for this to work without adding more code. The 2 in this example are from the same source with different filters selected. This allows me to sort, filter and dedup using my own methods. You can then re-create the xml or simply display it on the screen like the example does below.

If you still need help feel free to comment below.

Code and Example below

<?php
//Sort Function by title
function sortFunction( $a, $b )
{
return strtotime($b["title"]) - strtotime($a["title"]);
}

$urllist = array();
//Define new xml files here by adding a new line with different urls
$urllist[] = “http://www.instructables.com/tag/type-question/rss.xml?count=100&sort=RECENT”;
$urllist[] = “http://www.instructables.com/tag/type-question/rss.xml?count=100&sort=UNANSWERED”;

//Loop through urllist array adding each item to one multidimensional array
//Define array before populating
$items = array();
foreach($urllist as $url)
{
$feed = simplexml_load_file($url);

//these item names are the child names in the xml
//channel is the wrapper in the xml
foreach($feed->channel->item as $item)
{
$items[] = array(
‘link’ => (string)$item->link,
‘image’ => (string)$item->imageThumb,
‘title’ => (string)$item->title,
‘pubdate’ => (string)$item->pubDate,
‘author’ => (string)$item->author
);
}
}

//Sort by Title
usort($items, “sortFunction”);

//Remove Duplicates
$items = array_map(“unserialize”, array_unique(array_map(“serialize”, $items)));

//Loop through the list and display them
$ictr = 0;
foreach ($items as $item)
{
echo “<div style=’float:left; width:200px; height:300px; margin-right:15px; text-align:center;’>”;
echo “<a href='” . $item[‘link’] . “‘ target=’_blank’>”;

if(strpos($item[‘image’],”defaultIMG”))
{
echo “<img src=’http://www.instructables.com/static/img/footer/footer-robot.png’ />”;
}
elseif(strpos($item[‘image’],”com”))
{
echo “<img src='” . $item[‘image’] . “‘ />”;
}
else
{
echo “<img src=’http://www.instructables.com” . $item[‘image’] . “‘ />”;
}
echo ‘<br />’ . $item[‘title’] . ‘<br />’;
echo ‘By: ‘ . $item[‘author’] . ‘ On ‘ . $item[‘pubdate’] . ‘</a></div>’;
}
echo “<div style=’clear: both;’>&nbsp;</div>”;
?>


Example of the output:

 
Bookmark the permalink.

Leave a Reply