patw 的筆記、生活、隨筆
[Facebook] 計算粉絲團內特定文章的按"讚"數
最近新案的需求: 計算數個粉絲團中的特定文章按"讚"數, 最後加總達某個數字便可如何如何…
去開發者討論區問之後得到方向了, 詳細說明在這:
http://developers.facebook.com/docs/reference/api/page?ref=mf
實際做法如下:
ps.PHP 5.2 之後似乎就有支援 json_decode 了, 由於此案用的主機只有 5.1.6, 所以我是另外去抓 PEAR 的 JSON.php 去解. HttpRequest 也是另外抓的.
code 臨時寫來測試的 .. 有點亂請見諒 ~
ps.facebook GRAPH API 可以得到的資料真可怕… 有空再研究這塊~
(按:307559445728是某粉絲團的ID, 本例為取得裡面ID為307559445728_479251685728的這篇POST的按"讚"數)
<?php
if (!function_exists('json_decode')) {
function json_decode($content, $assoc=false) {
require_once 'JSON.php';
if ($assoc) {
$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
}
else {
$json = new Services_JSON;
}
return $json->decode($content);
}
}
if (!function_exists('json_encode')) {
function json_encode($content) {
require_once 'JSON.php';
$json = new Services_JSON;
return $json->encode($content);
}
}
require_once 'HttpRequest.php';
require_once 'HttpResponse.php';
require_once 'HttpClient.php';
function getPostLikes($url)
{
$likes = 0;
$http = new HttpClient();
$request = new HttpRequest();
$request->setMethod('GET');
$request->setUrl($url);
$response = $http->doRequest($request);
$pageContents = $response->getBody();
$json = json_decode($pageContents);
$likes = $json->{'likes'};
return $likes;
}
?>
改成一個 funciton
可用
$likes = getPostLikes("https://graph.facebook.com/307559445728_479251685728");
呼叫
| Print article | This entry was posted by patw on 2010年八月18日 at 2:11 下午, and is filed under Facebook, PHP. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |