Sometimes you might wanna list things on your site order by the popularity on Facebook. It can also be a handy tool compare your different sites Facebook likes and get social stats from it. Facebook offer a very handy service to check this without being logged in to Facebook in any way. Check the service we use here. Facebook will retreive all Facebook likes, share count and total counts of these. For each link, it will display:

<link_stat>
<url>http://www.google.com</url>
<share_count>295804</share_count>
<like_count>153002</like_count>
<comment_count>177545</comment_count>
<total_count>626351</total_count>
<click_count>265614</click_count>
<normalized_url>http://www.google.com/</normalized_url>
<comments_fbid>381702034999</comments_fbid>
</link_stat>

Get total likes on urls

With a loop in php we can get the information we need:

function getLikes($arr){
      $urls = "";

      // Add urls to check for likes
      for($i = 0;$i < count($arr);$i++) {
            if($urls != "") $urls .= ",";
            $urls .= $arr[$i];
      }

      // Retreive info from Facebook
      $facebookapi = "http://api.facebook.com/restserver.php?method=links.getStats&urls=" . $urls;
      $xml = simplexml_load_file($facebookapi);

      $likes = array();
      // Loop through the result and populate an array with the likes
      for ($i = 0;$i  < count($arr);$i++) {            
            $url = $xml->link_stat[$i]->url;
            $counts = (int)$xml->link_stat[$i]->like_count;
            $likes[] = array("likes" => $counts, "url" => $url);
      }

      return $likes;

}

// Array with links to the URLs we want to get number of likes from
$array = array("http://www.google.com","http://www.apple.com","http://www.facebook.com");
$likes = getLikes($array);

foreach ($likes as $key => $val) {
      echo $key . " => " . $val["url"] . " => " . $val["likes"] . "<br />";
}

Sorting the likes

After retrieving the likes, the array can be sorted by most popular url.

$likes = array_sort($likes, "likes", SORT_DESC);

foreach ($likes as $key => $val) {
      echo $key . " => " . $val["url"] . " => " . $val["likes"] . "<br />";
}

Download source