草庐IT

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

coder 2024-04-11 原文

我想获取 PHP 中给定 URL 在 google plus 上的分享数。我发现这个函数可以做到这一点:

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

但是,我总是收到相同的消息:注意: undefined index :导致...

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

有什么建议吗?

最佳答案

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

更新(2013 年 1 月 23 日):Google 于 2012 年 12 月屏蔽了此网址 - 因此此方法不再有效!
更新 (15.05.2013): 该方法再次有效!

<?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;
}

更新 (18.01.2014):这是一个使用 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;
}

更新 (02.11.2017):+1 计数正式失效!正如在 this Google+ Post 中宣布的那样由产品经理 John Nack 撰写 Google 最近从他们的网络共享按钮中删除了共享计数(又名 +1 计数)。 (他们声称此举的目的是让 +1 按钮和分享框加载得更快。)

关于php - 在 PHP 中获取给定 URL 的 google plus 共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12391779/

有关php - 在 PHP 中获取给定 URL 的 google plus 共享的更多相关文章

  1. ruby-on-rails - rails : save file from URL and save it to Amazon S3 - 2

    从给定URL下载文件并立即将其上传到AmazonS3的更直接的方法是什么(+将有关文件的一些信息保存到数据库中,例如名称、大小等)?现在,我既不使用Paperclip,也不使用Carrierwave。谢谢 最佳答案 简单明了:require'open-uri'require's3'amazon=S3::Service.new(access_key_id:'KEY',secret_access_key:'KEY')bucket=amazon.buckets.find('image_storage')url='http://www.ex

  2. ruby - 如何使用 Ruby aws/s3 Gem 生成安全 URL 以从 s3 下载文件 - 2

    我正在编写一个小脚本来定位aws存储桶中的特定文件,并创建一个临时验证的url以发送给同事。(理想情况下,这将创建类似于在控制台上右键单击存储桶中的文件并复制链接地址的结果)。我研究过回形针,它似乎不符合这个标准,但我可能只是不知道它的全部功能。我尝试了以下方法:defauthenticated_url(file_name,bucket)AWS::S3::S3Object.url_for(file_name,bucket,:secure=>true,:expires=>20*60)end产生这种类型的结果:...-1.amazonaws.com/file_path/file.zip.A

  3. ruby - 通过 ruby​​ 进程共享变量 - 2

    我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是

  4. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

  5. ruby - 从 Ruby 中的主机名获取 IP 地址 - 2

    我有一个存储主机名的Ruby数组server_names。如果我打印出来,它看起来像这样:["hostname.abc.com","hostname2.abc.com","hostname3.abc.com"]相当标准。我想要做的是获取这些服务器的IP(可能将它们存储在另一个变量中)。看起来IPSocket类可以做到这一点,但我不确定如何使用IPSocket类遍历它。如果它只是尝试像这样打印出IP:server_names.eachdo|name|IPSocket::getaddress(name)pnameend它提示我没有提供服务器名称。这是语法问题还是我没有正确使用类?输出:ge

  6. ruby - 获取模块中定义的所有常量的值 - 2

    我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c

  7. ruby-on-rails - Ruby url 到 html 链接转换 - 2

    我正在使用Rails构建一个简单的聊天应用程序。当用户输入url时,我希望将其输出为html链接(即“url”)。我想知道在Ruby中是否有任何库或众所周知的方法可以做到这一点。如果没有,我有一些不错的正则表达式示例代码可以使用... 最佳答案 查看auto_linkRails提供的辅助方法。这会将所有URL和电子邮件地址变成可点击的链接(htmlanchor标记)。这是文档中的代码示例。auto_link("Gotohttp://www.rubyonrails.organdsayhellotodavid@loudthinking.

  8. ruby-on-rails - 获取 inf-ruby 以使用 ruby​​ 版本管理器 (rvm) - 2

    我安装了ruby​​版本管理器,并将RVM安装的ruby​​实现设置为默认值,这样'哪个ruby'显示'~/.rvm/ruby-1.8.6-p383/bin/ruby'但是当我在emacs中打开inf-ruby缓冲区时,它使用安装在/usr/bin中的ruby​​。有没有办法让emacs像shell一样尊重ruby​​的路径?谢谢! 最佳答案 我创建了一个emacs扩展来将rvm集成到emacs中。如果您有兴趣,可以在这里获取:http://github.com/senny/rvm.el

  9. Ruby 从大范围中获取第 n 个项目 - 2

    假设我有这个范围:("aaaaa".."zzzzz")如何在不事先/每次生成整个项目的情况下从范围中获取第N个项目? 最佳答案 一种快速简便的方法:("aaaaa".."zzzzz").first(42).last#==>"aaabp"如果出于某种原因你不得不一遍又一遍地这样做,或者如果你需要避免为前N个元素构建中间数组,你可以这样写:moduleEnumerabledefskip(n)returnto_enum:skip,nunlessblock_given?each_with_indexdo|item,index|yieldit

  10. ruby - Net::HTTP 获取源代码和状态 - 2

    我目前正在使用以下方法获取页面的源代码:Net::HTTP.get(URI.parse(page.url))我还想获取HTTP状态,而无需发出第二个请求。有没有办法用另一种方法做到这一点?我一直在查看文档,但似乎找不到我要找的东西。 最佳答案 在我看来,除非您需要一些真正的低级访问或控制,否则最好使用Ruby的内置Open::URI模块:require'open-uri'io=open('http://www.example.org/')#=>#body=io.read[0,50]#=>"["200","OK"]io.base_ur

随机推荐