How to get Google +1 count for current page in PHP?

John picture John · Jan 13, 2012 · Viewed 19.4k times · Source

I want to get count of Google +1s for current web page ? I want to do this process in PHP, then write number of shares or +1s to database. That's why, I need it. So, How can I do this process (getting count of +1s) in PHP ?
Thanks in advance.

Answer

paulgagu picture paulgagu · Jul 9, 2013

This one works for me and is faster than the CURL one:

function getPlus1($url) {
    $html =  file_get_contents( "https://plusone.google.com/_/+1/fastbutton?url=".urlencode($url));
    $doc = new DOMDocument();   $doc->loadHTML($html);
    $counter=$doc->getElementById('aggregateCount');
    return $counter->nodeValue;
}

also here for Tweets, Pins and Facebooks

function getTweets($url){
    $json = file_get_contents( "http://urls.api.twitter.com/1/urls/count.json?url=".$url );
    $ajsn = json_decode($json, true);
    $cont = $ajsn['count'];
    return $cont;
}

function getPins($url){
    $json = file_get_contents( "http://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url=".$url );
    $json = substr( $json, 13, -1);
    $ajsn = json_decode($json, true);
    $cont = $ajsn['count'];
    return $cont;
}

function getFacebooks($url) { 
    $xml = file_get_contents("http://api.facebook.com/restserver.php?method=links.getStats&urls=".urlencode($url));
    $xml = simplexml_load_string($xml);
    $shares = $xml->link_stat->share_count;
    $likes  = $xml->link_stat->like_count;
    $comments = $xml->link_stat->comment_count; 
    return $likes + $shares + $comments;
}

Note: Facebook numbers are the sum of likes+shares and some people said plus comments (I didn't search this yet), anyway use the one you need.

This will works if your php settings allow open external url, check your "allow_url_open" php setting.

Hope helps.