代码之家  ›  专栏  ›  技术社区  ›  Pepe López

在PHP中获取给定URL的google plus共享

  •  4
  • Pepe López  · 技术社区  · 14 年前

    我想得到一个给定的PHP URL在GooglePlus上的共享数量。我发现这个函数可以做到这一点:

    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'] );
    }
    

    然而,我总是收到同样的信息: Notice: Undefined index: result in ... 。

    我制作 print_r($json) ,我得到: Array ( [0] => Array ( [error] => Array ( [code] => 400 [message] => Invalid Value [data] => Array ( [0] => Array ( [domain] => global [reason] => invalid [message] => Invalid Value ) ) ) [id] => p ) 。

    有什么建议吗?

    3 回复  |  直到 12 年前
        1
  •  8
  •   eyecatchUp    9 年前

    RPC API从未打算供公众使用,谷歌更改了身份验证以防止滥用。因此,您发布的代码不再有效。然而,我找到了一个简单得多的解决方案:

    更新(2013年1月23日): 谷歌在2012年12月屏蔽了这个URL,所以这个方法不再有效了!
    更新(2013年5月15日): 这个方法又起作用了!

    <?php
    /**
     * Get the numeric, total count of +1s from Google+ users for a given URL.
     * @author          Stephan Schmitz <eyecatchup@gmail.com>
     * @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;
    }
    

    更新(2014年1月18日): 这里有一个改进的版本,它使用了curl,一个后备主机,并进行了一些错误处理(最新版本可以在这里找到 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 <eyecatchup@gmail.com>
     * @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="http://stackoverflow.com/a/13385591/624466">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;
    }
    

    更新(2017年11月2日): +1计数正式失效!如中所述 this Google+ Post 由产品经理John Nack谷歌最近从他们的网络共享按钮中删除了共享计数(又名+1计数)。 (他们声称此举的目的是为了更快地加载+1按钮和共享框。)

        2
  •  1
  •   mimming    14 年前

    这个代码不起作用。此外,没有提供此计数的公开可用API。

    此代码使用驱动+1按钮的RPC API。此API不是官方支持的API,不打算在内部实现之外使用 Google+ plugins 。

        3
  •  0
  •   Luke Mlsna    13 年前

    其他帖子中列出的cURL和API方式不再有效。

    There is still at least 1 method ,但它很难看,谷歌显然不支持它。你只需用正则表达式从官方按钮的JavaScript源代码中提取变量:

    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;
    }
    
    推荐文章