2013年5月4日 星期六

取得Facebook按讚數(以PHP為例)

我們經常在網站中增加社群元件,比如說Facebook Like Button
我們透過以下工具產生按讚代碼 https://developers.facebook.com/docs/reference/plugins/like/
但怎麼取得按讚的數量呢?其實相當簡單,我們丟給facebook api請他回答給我們 預設回傳格式為xml
<?php
  $source_url = "www.example.com/xxx.html"; //想知道按讚數的網址
  $url = "http://api.facebook.com/restserver.php?method=links.getStats&urls=".urlencode($source_url );
  $get_xml = file_get_contents($url);
  $xml_result = simplexml_load_string($get_xml);
  $count = $xml_result->link_stat->total_count;
?> 
範例中我們取得的total_count為全部的按讚數(包含評論等等),請依實際需求使用。 
若是要改寫成json格式,也可以寫成這樣:
<?php
$fburl = 'www.example.com/xxx.html';
$json_string = file_get_contents('http://api.facebook.com/restserver.php?method=links.getStats&urls=' . urlencode($url));
//或是已知道該網址ids就可寫成 $json_string = file_get_contents('http://graph.facebook.com/?ids=' . $url);
$json = json_decode($json_string, true);
?> 
亦或是使用fql語法:
<?php
$fql  = "SELECT url, normalized_url, share_count, like_count, comment_count, ";
$fql .= "total_count, commentsbox_count, comments_fbid, click_count FROM ";
$fql .= "link_stat WHERE url = '".$url."'";
$apifql="https://api.facebook.com/method/fql.query?format=json&query=".urlencode($fql);
$fb_json=file_get_contents($apifql);
?> 

沒有留言:

張貼留言