You may have noticed my new blogroll on the left. That's generated straight from my list of feeds produced by my new RSS aggregator, NewsDesk. The source OPML file for that is at /mySubscriptions.opml (that seems to be the standard place for these things).
As you can see, the OPML file isn't sorted either by category or by feed name within the category. It would be nice if it were sorted (it's sorted within the program), but whatever, life isn't perfect. You'll notice that the blogroll on my left is sorted by category, and the feeds within each category are also sorted. So, I had to write code to sort that.
Sorting this OPML file isn't as simple as sorting a list of numbers. You can do that easily with built in sort routines. To sort my blogroll, I used a trick I've used before. You sort the indices, but leave the data alone.
I use my XML parser (part of my XML-RPC library) to parse the OPML file. Anyway, I'm not sure how to explain it much more beyond just showing code:
<?php
$cms->incLibrary('xml');
$c = &file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/mySubscriptions.opml');
$b = &XML_unserialize($c);
$cat = &$b['opml']['body']['outline'];
$cat_count = count_numeric_items($cat);
$categories = array();
for($n=0;$n<$cat_count;$n++){
$categories[$n] = array('text'=>$cat["$n attr"]['text'], 'index'=>$n);
}
usort($categories, 'blogroll_cmp');
function blogroll_cmp(&$a,&$b){
return strnatcasecmp($a['text'],$b['text']);
}
?>
You get the idea. Then I iterate over $categories, not $cat, but index into $cat, and do basically the exact same thing for the feeds within a category, printing out HTML along the way, etc.
Anyway, I just wanted to relay the technique of sorting indices, rather than sorting the actual data, because it comes in handy in a lot of places. If anything, sometimes it can simply be more efficient because you don't have to actually move a lot of data around within the system.
Feel free to post a comment below. Please see my comment policy.
Formatting Rules (No HTML):