1. List all files in the directory.
2. Call the Facebook API and find out the score for each file. (I couldn't find a way to do this for a whole directory at once.) You don't need an API key for this so it's very straight forward.
3. Sort according to score.
4. Print a table with the title of the html file (with a link to the proper URL) and the corresponding score.
Since I have 800 files, this take about one minute to complete. Therefore I don't run it in real time on my website. Instead I run it in cron once every day and writes the output to a file that is included using SSI into my page.
Example of usage can be seen at http://www.karinboye.se/index.shtml (in Swedish).
# Name of your website as in example.com
$site = 'example.com';
# Name of the subdiretory as in /directory/directory
$dir = '/dir/dir';
# Define some variables
$baseurl = 'http://api.facebook.com/restserver.php?
method=links.getStats&format=json&urls=';
$i = 0;
# Loop through all files in the directory
if ($handle = opendir('.'.$dir)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
# Call the Facebook API to get the data
$url = $baseurl.$site.$dir.'/'.$entry;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
$string = curl_exec($ch);
curl_close($ch);
$result = json_decode($string, TRUE);
# Of all the data returned I only need the total count here
$count = $result[0]['total_count'];
# Store the filename and score into two arrays
$file[$i] = $entry;
$score[$i] = $count;
$i++;
}
}
closedir($handle);
}
# Sort the arrays according to highest score
array_multisort($score, SORT_DESC, $file);
# Open a file to store the result in
$f = fopen('fb.shtml', 'w');
# Write the header
fwrite($f, "<!-- Created at: ".date("F j, Y, G:i")." -->\n");
fwrite($f, "<table border=\"0\" cellspacing=\"5\">\n");
# Loop through the top 10 scores
for ($i=0; $i<=9; $i++) {
# Get the title from the file
$url = '.'.$dir.'/'.$file[$i];
preg_match('/<title>(.+)<\/title>/iU',file_get_contents($url),
$matches);
$title = $matches[1];
# Write the data
fwrite($f, "<tr><td class=\"normaltext\"><a href=\"$url\">");
fwrite($f, "$title</a></td>");
fwrite($f, "<td class=\"normaltext\" align=\"right\">$score[$i]</td>
</tr>\n");
}
fwrite($f, "</table>\n");
fclose($f);