将Facebook API称为回声,就像计数不起作用一样

时间:2015-06-21 09:02:17

标签: php json facebook facebook-graph-api

我想在我的网站上显示我的Facebook页面的喜欢数量。我使用的上一个方法已经有几天没用了。

当我像这样调用Facebook图形API时: https://api.facebook.com/method/links.getStats?urls=http://www.facebook.com/549585444&format=json

它给了我以下输出(虚构的例子):

[{"url":"http:\/\/www.facebook.com\/549585444","normalized_url":"http:\/\/www.facebook.com\/549585444","share_count":0,"like_count":122,"comment_count":0,"total_count":122,"click_count":0,"comments_fbid":null,"commentsbox_count":0}]

现在我想回应一下这样的计数:

<?php
    $fb_page = "549585444"; 
    $url = "https://api.facebook.com/method/links.getStats?urls=http://www.facebook.com/".$fb_page."&format=json";
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);   
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    $json_returned = curl_exec($curl);  
    curl_close($curl);
    $json_returned = json_decode($json_returned, true);
    echo $json_returned['like_count'];
?>

但这个数字并没有出现。知道为什么吗?

1 个答案:

答案 0 :(得分:1)

正如您在JSON输出中看到的那样,答案包含在一个数组中:

array(1) {
  [0]=>
  array(9) {
    ["url"]=>
    string(33) "http://www.facebook.com/549585444"
    ["normalized_url"]=>
    string(33) "http://www.facebook.com/549585444"
    ["share_count"]=>
    int(0)
    ["like_count"]=>
    int(0)
    ["comment_count"]=>
    int(0)
    ["total_count"]=>
    int(0)
    ["click_count"]=>
    int(0)
    ["comments_fbid"]=>
    NULL
    ["commentsbox_count"]=>
    int(0)
  }
}

要获得数字输出,您必须通过更改此行来获取数组中的第一项:

echo $json_returned['like_count'];

对此:

echo $json_returned[0]['like_count'];