Getting facebook likes,shares and comments count using php

by guruprasad 2014-08-28 18:34:20

To Get facebook likes,shares and comments count using php:


Creating class:
 
class getFBCount
{
    private $url,$timeout;
    function __construct($url,$timeout=10)
    {
        $this->url=rawurlencode($url);
        $this->timeout=$timeout;
    }
    function get_fb_shares()
    {
        $json_string = $this->file_get_contents_curl('https://api.facebook.com/restserver.php?method=links.getStats&format=json&urls='.$this->url);
        $json = json_decode($json_string, true);
        return isset($json[0]['share_count'])?intval($json[0]['share_count']):0;
    }
    
    function get_fb_likes()
    {
        $json_string = $this->file_get_contents_curl('https://api.facebook.com/restserver.php?method=links.getStats&format=json&urls='.$this->url);
        $json = json_decode($json_string, true);
        return isset($json[0]['like_count'])?intval($json[0]['like_count']):0;
    }
    
    function get_fb_comments()
    {
        $json_string = $this->file_get_contents_curl('https://api.facebook.com/restserver.php?method=links.getStats&format=json&urls='.$this->url);
        $json = json_decode($json_string, true);
        return isset($json[0]['comment_count'])?intval($json[0]['comment_count']):0;
    }
    
    private function file_get_contents_curl($url)
    {
        $ch=curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($ch, CURLOPT_FAILONERROR, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $cont = curl_exec($ch);
        if(curl_error($ch))
        {
        die(curl_error($ch));
        }
        return $cont;
    }
}
calling class functions for getting shares,likes and comment count

 
$obj=new getFBCount("your webpage name");
echo "
Facebook Shares: ".$obj->get_fb_shares();
echo "
Facebook Likes: ".$obj->get_fb_likes();
echo "
Facebook Comments: ".$obj->get_fb_comments();
Output :
Facebook Shares: 15
Facebook Likes: 44
Facebook Comments: 0
 
1218
like
0
dislike
0
mail
flag

You must LOGIN to add comments