Facebook好友计数器


Facebook friend counter

我想做的是在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
?>

因此,echo$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...]

您有一个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

您可以通过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}