Fair trade news
September 5th, 2008I’ve just added a news section to Hand Up Media’s site, bringing in the latest in the fair trade world as supplied by the BBC and the Guardian. HUM previously had an HTML-only host, so the only way to include this news section was using javascript. Two problems – no javascript, no news, and also search engines, which rate fresh content highly, generally don’t run javascript.
Their host eventually upgraded and offered PHP, so I took the opportunity to grab the feeds on the server side, solving both those problems. PHP5 has much improved XML parsing over previous versions: the simplexml_load_file function reads in an xml file and makes it available as an object:
$bbc = "http://newsapi.bbc.co.uk/feeds/search/news+sport/fairtrade";
$bbcrss = simplexml_load_file($bbc);
Then, in the case of RSS, take the item element and loop through its contents:
$bbcitems = $bbcrss->channel->item;
foreach ($bbcitems as $item){
$item->source='the BBC';
if (time() - strtotime($item->pubDate) < 5259487){
$news[]=$item;
}
}
Also in there, I just check that the story is less than two months old before adding it to the $news array, and add a ’source’ element because that’s not included in the RSS in any proper form. Last thing to do (after adding news from other sources to the same array) is to sort it in date order using usort:
function _cmpAscA($m, $n) {
if (strtotime($m->pubDate) == strtotime($n->pubDate)) {
return 0;
}
return (strtotime($m->pubDate) > strtotime($n->pubDate)) ? -1 : 1;
}
usort($news,'_cmpAscA');
This function takes the array and a function as arguments: the function checks each element’s pubDate value (converting it to a UNIX timestamp) and changing its order in the original array accordingly. Then all that remains is to output it in a list and style it up…




