Friday, January 4, 2013

PHP code for listing Facebook scores

On my website I have a directory of about 800 html files, and I wanted to create a list of the most popular ones according to Facebook "like" and "share" counts. Below is my pseudo php code for this. The steps are the following:

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 (in Swedish).

 # Name of your website as in  
 $site  = '';  
 # Name of the subdiretory as in /directory/directory  
 $dir   = '/dir/dir';  
 # Define some variables  
 $baseurl = '
 $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);  
       $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;  
 # 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];  
   $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>
 fwrite($f, "</table>\n");  

No comments:

Post a Comment