Getting google plus shares for a given URL in PHP
Asked Answered
C

3

4

I want to get the number of shares on google plus for a given URL in PHP. I found this function to do that:

function get_shares_google_plus($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);
  print_r($json);
  return intval( $json[0]['result']['metadata']['globalCounts']['count'] );
}

However, I always get the same message: Notice: Undefined index: result in ....

I make print_r($json), and I get: Array ( [0] => Array ( [error] => Array ( [code] => 400 [message] => Invalid Value [data] => Array ( [0] => Array ( [domain] => global [reason] => invalid [message] => Invalid Value ) ) ) [id] => p ).

Any suggestions?

Cherice answered 12/9, 2012 at 15:37 Comment(0)
B
8

The RPC API was never meant for public use and Google changed authentication in order to prevent abuse. Thus, the code that you posted does not work any longer. However, I found a much simpler solution:

Update (23.01.2013): Google blocked this URL in december 2012 - so this method doesn't work any longer!
Update (15.05.2013): The method works again!

<?php
/**
 * Get the numeric, total count of +1s from Google+ users for a given URL.
 * @author          Stephan Schmitz <[email protected]>
 * @copyright       Copyright (c) 2013 Stephan Schmitz
 * @license         http://eyecatchup.mit-license.org/  MIT License
 * @link            <a href="https://gist.github.com/eyecatchup/8495140">Source</a>.
 * @param   $url    string  The URL to check the +1 count for.
 * @return  intval          The total count of +1s.
 */
function getGplusShares($url) {
    $url = sprintf('https://plusone.google.com/u/0/_/+1/fastbutton?url=%s', urlencode($url));
    preg_match_all('/{c: (.*?),/', file_get_contents($url), $match, PREG_SET_ORDER);
    return (1 === sizeof($match) && 2 === sizeof($match[0])) ? intval($match[0][1]) : 0;
}

Update (18.01.2014): Here's an improved version that uses curl, a fallback host and does some error handling (the latest version can be found here https://gist.github.com/eyecatchup/8495140).

<?php
/**
 * GetPlusOnesByURL()
 *
 * Get the numeric, total count of +1s from Google+ users for a given URL.
 *
 * Example usage:
 * <code>
 *   $url = 'http://www.facebook.com/';
 *   printf("The URL '%s' received %s +1s from Google+ users.", $url, GetPlusOnesByURL($url));
 * </code>
 *
 * @author          Stephan Schmitz <[email protected]>
 * @copyright       Copyright (c) 2014 Stephan Schmitz
 * @license         http://eyecatchup.mit-license.org/  MIT License
 * @link            <a href="https://gist.github.com/eyecatchup/8495140">Source</a>.
 * @link            <a href="https://mcmap.net/q/168360/-getting-google-plus-shares-for-a-given-url-in-php">Read more</a>.
 *
 * @param   $url    string  The URL to check the +1 count for.
 * @return  intval          The total count of +1s.
 */
function GetPlusOnesByURL($url) {
    !$url && die('No URL, no results. ;)');

    !filter_var($url, FILTER_VALIDATE_URL) &&
        die(sprintf('PHP said, "%s" is not a valid URL.', $url));

    foreach (array('apis', 'plusone') as $host) {
        $ch = curl_init(sprintf('https://%s.google.com/u/0/_/+1/fastbutton?url=%s',
                                      $host, urlencode($url)));
        curl_setopt_array($ch, array(
            CURLOPT_FOLLOWLOCATION => 1,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => 0,
            CURLOPT_USERAGENT      => 'Mozilla/5.0 (Windows NT 6.1; WOW64) ' .
                                      'AppleWebKit/537.36 (KHTML, like Gecko) ' .
                                      'Chrome/32.0.1700.72 Safari/537.36' ));
        $response = curl_exec($ch);
        $curlinfo = curl_getinfo($ch);
        curl_close($ch);

        if (200 === $curlinfo['http_code'] && 0 < strlen($response)) { break 1; }
        $response = 0;
    }
    !$response && die("Requests to Google's server fail..?!");

    preg_match_all('/window\.__SSR\s\=\s\{c:\s(\d+?)\./', $response, $match, PREG_SET_ORDER);
    return (1 === sizeof($match) && 2 === sizeof($match[0])) ? intval($match[0][1]) : 0;
}

Update (02.11.2017): The +1 count is officially dead! As announced in this Google+ Post by Product Manager John Nack Google recently removed the share count (aka +1 Count) from their web Sharing buttons. (They claim that the purpose of this move is for making the +1 button and share box load more quickly.)

Botti answered 14/11, 2012 at 19:8 Comment(8)
Hm, seems like they blocked it. However, if you use HTTPS it still works (updated answer).Botti
Nice workaround! It can also break if Google change stuff, but until it does...(really don't understand why google doesn't give easy access to this like fb and twitter)Crosson
Yep, I don't understand it neither. Especially when you look at the fact that Google defined this tag <meta name="interactionCount" content="UserPlusOnes:NUMBER_THAT_I_CANT_GET" > for schema.org. So tell me Google, how will we write this tag if we can’t request the count?Botti
@PepeLópez: Yes, it was blocked back in december already. However, there is another way to get the count. ;-)Botti
Any updates in Feb 2014 for this? I get 0 for any URL. What a pain huh!Hatty
@BenRacicot Check your error messages. The code still works for me - as is: i.imgur.com/xrjFeX9.jpgBotti
Any updates on this one. Really need it. Noticed that not even in the developers console there is no possibility of getting this.Donelu
@Donelu As announced in this Google+ Post by Product Manager John Nack Google recently removed the share count (aka +1 Count) from their web Sharing buttons. (They claim that the purpose of this move is for making the +1 button and share box load more quickly.)Botti
S
1

This code is not going to work. Additionally, there's no publicly available API that provides this count.

This code uses the RPC API that powers the +1 button. This API is not an officially supported API, and is not intended to be used outside of the internal implementation of Google+ plugins.

Sublimity answered 13/9, 2012 at 19:18 Comment(0)
Y
0

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;
}
Yarndyed answered 16/3, 2013 at 12:34 Comment(1)
That is exactly the code that I posted a couple of months ago. Why creating duplicated answers?Botti

© 2022 - 2024 — McMap. All rights reserved.