【问题标题】:Facebook friend counter脸书好友柜台
【发布时间】:2012-02-10 17:44:01
【问题描述】:

我正在尝试做的是 php 中的 facebook 好友计数器,因此代码的结果将类似于“你有 1342 个好友!”。

这是我使用的代码:

<?php 

require_once("../src/facebook.php");

    $config = array();
    $config[‘appId’] = 'MY_APP_ID';
    $config[‘secret’] = 'MY_APP_SECRET';
    $facebook = new Facebook($config);
    $user_id = "MY_USER_ID";

      //Get current access_token
    $token_response = file_get_contents
      ("https://graph.facebook.com/oauth/access_token?
      client_id=$config[‘appId’]
      &client_secret=$config[‘secret’]
      &grant_type=client_credentials"); 


  // known valid access token stored in $token_response
  $access_token = $token_response;

  $code = $_REQUEST["code"];

  // If we get a code, it means that we have re-authed the user 
  //and can get a valid access_token. 
  if (isset($code)) {
    $token_url="https://graph.facebook.com/oauth/access_token?client_id="
      . $app_id  
      . "&client_secret=" . $app_secret 
      . "&code=" . $code . "&display=popup";
    $response = file_get_contents($token_url);
    $params = null;
    parse_str($response, $params);
    $access_token = $params['access_token'];
  }


  // Query the graph - Friends Counter:
$data = file_get_contents
("https://graph.facebook.com/$user_id/friends?" . $access_token );
$friends_count = count($data['data']); 
echo "Friends: $friends_count";

echo "<p>$data</p>"; //to test file_get_contents

?>

因此,回显 $Friends_count 的结果始终为“1”。

然后我用 echo 测试 $data,它给了我所有朋友的列表,所以它正在获取内容,但它的计数不正确......我该如何解决它?

我已经尝试过更换

$friends_count = count($data['data']); 

$friends_count = count($data['name']);

$friends_count = count($data['id']);

但结果始终为“1”。


上面代码的结果是这样的;

Friends: 1

{"data":[{"name":"Enny Pichardo","id":"65601304"},{"name":"Francisco Roa","id":"500350497"},etc...]

【问题讨论】:

标签: php facebook facebook-graph-api facebook-php-sdk facebook-friends


【解决方案1】:

你有一个 JSON 对象;一个字符串,不是 PHP 可以用count()“计算”的任何东西。您需要先解析 JSON:

$obj=json_decode($data);
$friends_count = count($obj->data); // This refers to the "data" key in the JSON

我快速搜索了一些参考资料:

http://php.net/manual/en/function.json-decode.php
http://roshanbh.com.np/2008/10/creating-parsing-json-data-php.html

【讨论】:

  • 万分感谢!!解决问题!对 JSON 对象并不陌生,现在正在学习它...再次感谢!!!
【解决方案2】:

你可以通过fql轻松获取好友数。

用户表有一个friend_count字段,您可以查询。

SELECT friend_count FROM user WHERE uid = me();

https://graph.facebook.com/fql?q=SELECT friend_count FROM user WHERE uid={any id}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多