Sandhya Singh Sandhya Singh - 3 months ago 78
PHP Question

how to count number of fb likes and show on a web page in php

How to count number of

f/b
likes and show on a web page
I have tried using access token but failed.

Any help would be appreciated!!
Thank you

I've tried:

<?php $url = 'http://graph.facebook.com/app-id"';
echo '['.$url.']: '.json_decode(file_get_contents($url))->{'likes'}; ?>


And other codes.

But shows only this error:


"Trying to get property of non-object"

Answer

Try this code, just call this function with your page id and access_token

First Answer

<?php 
function fbLikeCount($id,$access_token){
    //Request URL
    $json_url ='https://graph.facebook.com/'.$id.'?fiel‌​ds=likes&access_token='.$access_token;
    $json = file_get_contents($json_url);
    $json_output = json_decode($json);

    //Extract the likes count from the JSON object
    if($json_output->likes){
        return $likes = $json_output->likes;
    }else{
        return 0;
    }
}
//This Will return like count of Facebook page
echo fbLikeCount('page_id','access_token');
?>

Second Answer

function fbLikeCount($id,$access_token){
    //Request URL
    $json_url ='https://graph.facebook.com/'.$id.'?fields=fan_count&access_token='.$access_token;
    $json = file_get_contents($json_url);
    $json_output = json_decode($json);
    //Extract the likes count from the JSON object
    if($json_output->fan_count){
        return $likes = $json_output->fan_count;
    }else{
        return 0;
    }
}
echo fbLikeCount('page_id','app_id|app_secret');

I hope this will work for you.

Comments