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

8

18

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.

Abe answered 13/1, 2012 at 15:56 Comment(7)
Google it. developers.google.com/+/plugins/+1buttonItch
I want to do this process in PHP, then write number of shares or +1s to database. That's why, I need it.Abe
johndyer.name/…Cyder
@Cyder this code doesn't work.Abe
@ManseUK but, it returns "0" for every page.Abe
@John: Maybe here? #7321702Cyder
JaiV asks "is there still not an option to get +1 counts for url?"Leatri
H
19

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.

Hildehildebrand answered 8/7, 2013 at 23:22 Comment(4)
How do you do this for Linked in?Wikiup
@ChillWebDesigns ripped from my code, didn't format neatly but you can figure it out: $stream = @file_get_contents("http://www.linkedin.com/countserv/count/share?url={$url}&format=json"); $json = json_decode($stream, true); $results['linkedin'] = intval($json['count']);Nailbiting
I know this is old, but I just tried it and loadHtml had problems with the svg tags in the document. Here was my quick solution: $html = file_get_contents( "https://plusone.google.com/_/+1/fastbutton?url=".urlencode($url)); $html = explode('<div id="aggregateCount" class="Oy">', $html)[1]; return explode('</div>', $html)[0];Sonatina
This is still working but shows a lot of warnings. Instead of DOMDocument I use return preg_replace('/.*<div id="aggregateCount"[^>]+>(\d+)<\/div>.*/s', '$1', $html);Touchmenot
C
12
function get_plusones($url) {
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, "https://clients6.google.com/rpc");
  curl_setopt($curl, CURLOPT_POST, 1);
  curl_setopt($curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
  $curl_results = curl_exec ($curl);
  curl_close ($curl);
  $json = json_decode($curl_results, true);
  return intval( $json[0]['result']['metadata']['globalCounts']['count'] );
}

echo get_plusones("http://www.stackoverflow.com")

from internoetics.com

Cleanser answered 31/7, 2012 at 16:16 Comment(0)
S
6

The cURL and API way listed in the other posts here no longer works.

There is still at least 1 method, but it's ugly and Google clearly doesn't support it. You just rip the variable out of the JavaScript source code for the official button with a regular expression:

function shinra_gplus_get_count( $url ) {
    $contents = file_get_contents( 
        'https://plusone.google.com/_/+1/fastbutton?url=' 
        . urlencode( $url ) 
    );

    preg_match( '/window\.__SSR = {c: ([\d]+)/', $contents, $matches );

    if( isset( $matches[0] ) ) 
        return (int) str_replace( 'window.__SSR = {c: ', '', $matches[0] );
    return 0;
}
Skeie answered 16/3, 2013 at 12:31 Comment(2)
This answer seems to suggest the methods using cURL + API do not work no more, but currently I've got a working solution using these techniques to retrieve Google+ shares and +1's, see my answer further on (https://mcmap.net/q/652099/-how-to-get-google-1-count-for-current-page-in-php).Puryear
It really is ridiculous that they wouldn't add official support for such a basic feature when there's a huge demand for it.Broderickbrodeur
P
4

The next PHP script works great so far for retrieving Google+ count on shares and +1's.

$url = 'http://nike.com';
$gplus_type = true ? 'shares' : '+1s';

/**
 * Get Google+ shares or +1's.
 * See out post at https://mcmap.net/q/652099/-how-to-get-google-1-count-for-current-page-in-php
 */
function get_gplus_count($url, $type = 'shares') {
  $curl = curl_init();

  // According to https://mcmap.net/q/669327/-difficulty-getting-google-plus-one-count we should use certificates
  // to connect through SSL, but they also offer the following easier solution.
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

  if ($type == 'shares') {
    // Use the default developer key AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ, see
    // tomanthony.co.uk/blog/google_plus_one_button_seo_count_api.
    curl_setopt($curl, CURLOPT_URL, 'https://clients6.google.com/rpc?key=AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ');
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
  }
  elseif ($type == '+1s') {
    curl_setopt($curl, CURLOPT_URL, 'https://plusone.google.com/_/+1/fastbutton?url='.urlencode($url));
  }
  else {
    throw new Exception('No $type defined, possible values are "shares" and "+1s".');
  }

  $curl_result = curl_exec($curl);
  curl_close($curl);

  if ($type == 'shares') {
    $json = json_decode($curl_result, true);
    return intval($json[0]['result']['metadata']['globalCounts']['count']);
  }
  elseif ($type == '+1s') {
    libxml_use_internal_errors(true);
    $doc = new DOMDocument();
    $doc->loadHTML($curl_result);
    $counter=$doc->getElementById('aggregateCount');
    return $counter->nodeValue;
  }
}

// Get Google+ count.
$gplus_count = get_gplus_count($url, $gplus_type);
Puryear answered 15/4, 2014 at 15:46 Comment(0)
M
2

Google does not currently have a public API for getting the +1 count for URLs. You can file a feature request here. You can also use the reverse engineered method mentioned by @DerVo. Keep in mind though that method could change and break at anytime.

Moscow answered 14/1, 2012 at 2:22 Comment(0)
D
2

I've assembled this code to read count directly from the iframe used by social button. I haven't tested it on bulk scale, so maybe you've to slow down requests and/or change user agent :) . This is my working code:

function get_plusone($url) 
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://plusone.google.com/_/+1/fastbutton?   
bsv&size=tall&hl=it&url=".urlencode($url));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$html = curl_exec ($curl);
curl_close ($curl);
$doc = new DOMDocument();
$doc->loadHTML($html);
$counter=$doc->getElementById('aggregateCount');
return $counter->nodeValue;

}

Usage is the following:

echo get_plusones('http://stackoverflow.com/');

Result is: 3166

Dorsey answered 5/12, 2012 at 16:27 Comment(0)
B
1

I had to merge a few ideas from different options and urls to get it to work for me:

function getPlusOnes($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, "https://plusone.google.com/_/+1/fastbutton?url=".urlencode($url));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $html = curl_exec ($curl);
        curl_close ($curl);
        $doc = new DOMDocument();
        $doc->loadHTML($html);
        $counter=$doc->getElementById('aggregateCount');
        return $counter->nodeValue;
    }

All I had to do was update the url but I wanted to post a complete option for those interested.

echo getPlusOnes('http://stackoverflow.com/')

Thanks to Cardy for using this approach, then I just had to just get a url that worked for me...

Bouilli answered 16/3, 2013 at 10:21 Comment(0)
B
0

I've released a PHP library retrieving count for major social networks. It currently supports Google, Facebook, Twitter and Pinterest.

Techniques used are similar to the one described here and the library provides a mechanism to cache retrieved data. This library also have some other nice features: installable through Composer, fully tested, HHVM support.

http://dunglas.fr/2014/01/introducing-the-socialshare-php-library/

Bulletproof answered 17/1, 2014 at 8:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.