如何获得Facebook页面的数量

时间:2015-03-10 21:47:22

标签: facebook facebook-graph-api

我的以下脚本不再显示fb-page-likes的数量......

$ch = curl_init("http://graph.facebook.com/FACEBOOKPAGE");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$raw = curl_exec($ch);
curl_close($ch);
$data = json_decode($raw);
$scm_fb = $data->likes;
echo $scm_fb;

我还尝试了以下代码,但这也没有显示任何内容......

$page_id = "FACEBOOKPAGE"; 
$likes = 0; //Initialize the count

//Construct a Facebook URL
$json_url ='https://graph.facebook.com/'.$page_id.'';
$json = file_get_contents($json_url);
$json_output = json_decode($json);

//Extract the likes count from the JSON object
if($json_output->likes){
    $likes = $json_output->likes;
}

(我也试过Facebook-Page-ID而不是pagename,结果是一样的)

有什么建议吗?

3 个答案:

答案 0 :(得分:4)

您可以使用graph api获取具有相应访问权限的页面的详细信息。如果您已拥有有效的访问令牌,请使用以下代码获取页面详细信息。

$fb_page = ''; 
$access_token = '';
$url = "https://graph.facebook.com/v2.2/".$fb_page.'?access_token='.$access_token;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);   
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);  
curl_close($curl);
$details = json_decode($result,true);
echo "Likes:".$details['likes']; 

答案 1 :(得分:4)

您可以通过使用此php代码段解析Facebook Like Widget源代码来获取任何图形对象或网址:

<?php

    $id = "youtubetabapp";
    // customize: "https://facebook.com/[customize]"    
    $url = "https://facebook.com/$id"; // by name
    //$url = "https://facebook.com/282374908483303"; // or by id

    // customize: "locale=[customize]&" to your needs
    $ch = curl_init("https://www.facebook.com/v2.5/plugins/like.php?locale=$locale&href=".$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Safari');
    $html = curl_exec($ch);

    //die( var_dump( $html ) ); // <- debug fetched data
    // have a look for the data you need and customize your regex pattern accordingly
    // "preg_match([customize], $html, $match);"
    preg_match("/([0-9,.]+[a-zA-Z,\S]) people like this./", $html, $match);
    $likes = $match[1];
    //$likes = str_replace(array(".", "K"), array("", "000"), $likes); // <- customize output | remove ".", replace "K" with "000"
    //$likes = (float)$likes; // <- customize output | change type to float, strips prepending non-digits (eg: "K") as well
    die( $likes );

?>

与API方法相比,您不需要提供任何令牌,只需一个请求即可。基于我的测试 - 您只需要保留locale参数,以确保您有用于解析的常量源代码。

答案 2 :(得分:2)

如果没有将您的access_token提供给Facebook Graph API,您将无法获得任何页面。

您的网址应该是这样的

https://graph.facebook.com/v2.2/{YOUR_PAGE_ID}?fields=like&access_token={YOUR_ACCESS_TOKEN}

如果您想了解如何使用Graph API以及如何生成access_token,请尝试以下链接。

FACEBOOK GRAPH API - 页面

https://developers.facebook.com/docs/graph-api/reference/v2.2/page

访问令牌 - Pagetoken

https://developers.facebook.com/docs/facebook-login/access-tokens#pagetokens

GRAPH API EXPLORER

https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=765898450131958%3Ffields%3Dlikes&version=v2.2&