[Facebook] 取得粉絲專頁資訊與最新一筆主題的方法 (PHP/jQuery/ASP.NET(C#))

Standard

想要取得粉絲專頁(粉絲團頁面)的公開資訊,以及該粉絲團最新一筆主題該怎麼做呢?
這邊分成三種版本來講:PHP、jQuery 與 C#.NET。

※由於粉絲專頁幾乎是公開資訊,從 Graph API 就可取得。因此其實也可以不用做 app,直接就可以透過 Graph API 撈取。這邊只有 PHP 是用老作法。

PHP

嗯,您要先下載官方的 PHP SDK。就是 facebook.php 這隻。

然後不多說 .. 直接看 Code 吧。

[code language=”PHP”]
<?php
require ‘./facebook.php’;

$facebook = new Facebook(array(
‘appId’ => ‘APP ID’,
‘secret’ => ‘SECRET KEY’,
‘cookie’ => true, // enable optional cookie support
));

// 取得粉絲團相關資訊
function getPageInfo($page) {
$fbpageinfo = ”;

global $facebook;

try {
$fbpageinfo = $facebook->api("/$page");
}
catch(Exception $o) {
//print_r($o);
}

return $fbpageinfo;
}

// 取得粉絲團最新一筆話題
function getPageTopic($page) {
$fbpagetopic = ”;

global $facebook;

try {
$fbpagetopic = $facebook->api("/$page/posts?limit=1");
}
catch(Exception $o) {
//print_r($o);
}

return $fbpagetopic;
}

// 擷取部分字串後加刪節號
function textLimit($string, $length, $replacer = ‘…’)
{
if(strlen($string) > $length)
return (preg_match(‘/^(.*)\W.*$/’, mb_substr($string, 0, $length+1, ‘UTF-8’), $matches) ? $matches[1] : mb_substr($string, 0, $length, ‘UTF-8’)) . $replacer;

return $string;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Facebook Test</title>
</head>

<body>
<?php
$datas = array(‘DCView’,’digiphoto.tw’,’amberkuo1986′);
?>

<?php

for($i=0;$i<count($datas);$i++){

$page = ”;
$topic = ”;

$page = getPageInfo($datas[$i]);
$topic = getPageTopic($datas[$i]);
?>

<table width="400">
<tr><th><img src="<?php echo $page[‘picture’];?>" /><br /><?php echo $page[‘name’];?></th></tr>
<tr><td>有 <?php echo $page[‘likes’];?> 人說 <?php echo $page[‘name’];?> 讚</td></tr>
<tr><td>
<?php echo textLimit($topic[‘data’][0][‘message’],30);?>
</td></tr>
</table>

<?php
}
?>

</body>
</html>
[/code]


jQuery

再來是 jQuery 版本 .. 其實只是 JSON 去撈而已 XD

[code language=”html”]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>粉絲團資料 jQuery 版本</title>

<style type="text/css">
.team {
margin: 10px auto;
}
</style>

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" language="javascript">
google.load("jquery", "1.5");
</script>

<script type="text/javascript">
function team(name, picture, topic)
{
this.name = name;
this.picture = picture;
this.topic = topic;
}

var teams = new Array("amberkuo1986", "DCView");
var obj = new Object();

$(document).ready(function() {
for(var i=0; i<teams.length; i++){
retrieveData(teams[i]);
};
});

function retrieveData(id) {
var baseURL = ‘http://graph.facebook.com/’;
$.getJSON(baseURL+id+"&callback=?", function(data) {
obj[id] = new team(data.name, data.picture);
retrieveNewestTopic(id);
});
};

function retrieveNewestTopic(id) {
var baseURL = ‘http://graph.facebook.com/’;
$.getJSON(baseURL+id+"/posts?limit=1&callback=?", function(data) {
obj[id].message = data.data[0].message;

$(‘#teamList’).append(‘<div class="team"><img src="’ + obj[id].picture + ‘" /><br /> 粉絲團名稱:’ + obj[id].name + ‘<br />最新主題:’ + obj[id].message + ‘</div>’);
});
}
</script>
</head>
<body>

<div id=’teamList’>
</div>

</body>
</html>
[/code]


ASP.NET(C#)

這邊有使用到 JSON.NET 元件(Newtonsoft.Json.Net35.dll)

Default2.aspx
[code language=”html”]
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server" RepeatColumns="2" Width="80%">
<ItemStyle BorderStyle="Solid" BorderWidth="1px" VerticalAlign="Top"
Width="50%" />
<ItemTemplate>
<asp:Image ID="Image1" ImageUrl='<%#Eval("picture") %>’ runat="server" /><br />
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#Eval("link") %>’><%#Eval("name") %></asp:HyperLink><br /><br />
<asp:Label ID="Label1" runat="server" Text='<%#Eval("message") %>’></asp:Label>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>
[/code]

Default2.aspx.cs
[code language=”csharp”]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Runtime.Serialization.Json;

public partial class Default2 : System.Web.UI.Page
{

public class Page
{
public string Name { get; set; }
public string Picture { get; set; }
public string Link { get; set; }
}

public class Topic
{
public string Message { get; set; }
public string Picture { get; set; }
public string Link { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
string[] pages = {"amberkuo1986", "DCView"};

DataTable tb = new DataTable();
tb.Columns.Add("name", typeof(string));
tb.Columns.Add("picture", typeof(string));
tb.Columns.Add("link", typeof(string));
tb.Columns.Add("message", typeof(string));

for (int i = 0; i < pages.Count(); i++)
{
Page page = getRetrievePageInfo(pages[i]);
Topic topic = getRetrieveNewestTopic(pages[i]);
tb.Rows.Add(page.Name, page.Picture, page.Link, topic.Message);
}

DataList1.DataSource = tb;
DataList1.DataBind();
}

/// <summary>
/// 取得網頁內容方法
/// </summary>
/// <param name="Url"></param>
/// <returns></returns>
private string GetWebData(string Url)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(Url);
req.Method = "GET";
req.ContentType = "application/json";
using (WebResponse wr = req.GetResponse())
{
using (StreamReader myStreamReader = new StreamReader(wr.GetResponseStream()))
{
string data = myStreamReader.ReadToEnd();
return data;
}
}
}

/// <summary>
/// 取得粉絲頁資訊
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
private Page getRetrievePageInfo(string id)
{
JObject datas = JObject.Parse(GetWebData(String.Format("http://graph.facebook.com/{0}", id)));

Page r = new Page();
r = JsonConvert.DeserializeObject<Page>(datas.ToString());

return r;
}

/// <summary>
/// 取得最新一筆主題
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
private Topic getRetrieveNewestTopic(string id)
{
JObject datas = JObject.Parse(GetWebData(String.Format("http://graph.facebook.com/{0}/posts?limit=1", id)));

IList<JToken> results = datas["data"].Children().ToList();
Topic r = new Topic();

foreach (JToken result in results)
{
r = JsonConvert.DeserializeObject<Topic>(result.ToString());
}

return r;
}
}
[/code]


最後再補充一個 Facebook Graph Toolkit for .NET 的作法

是使用 Facebook Graph Toolkit 這個元件,這邊使用的是 Facebook Graph Toolkit 1.1 for .Net 3.5 這包。嗯..這樣比起上面那樣搞剛的做法好多了 XD

Default.aspx
[code language=”csharp”]
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:DataList ID="DataList1" runat="server" RepeatColumns="2" Width="80%">
<ItemStyle BorderStyle="Solid" BorderWidth="1px" VerticalAlign="Top"
Width="50%" />
<ItemTemplate>
<asp:Image ID="Image1" ImageUrl='<%#Eval("picture") %>’ runat="server" /><br />
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#Eval("link") %>’><%#Eval("name") %></asp:HyperLink> (有
<asp:Label ID="Label2" runat="server" Text='<%#Eval("likes") %>’></asp:Label> 人說讚)<br /><br />
<asp:Label ID="Label1" runat="server" Text='<%#Eval("message") %>’></asp:Label>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>
[/code]

Default.aspx.cs
[code language=”csharp”]
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook_Graph_Toolkit.GraphApi;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
private class FBPage
{
public string Name { get; set; }
public string Link { get; set; }
public string Picture { get; set; }
public int Likes { get; set; }
}

private class FBPost
{
public string Message { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
string[] teams = {"amberkuo1986", "DCView"};

DataTable tb = new DataTable();
tb.Columns.Add("name", typeof(string));
tb.Columns.Add("picture", typeof(string));
tb.Columns.Add("link", typeof(string));
tb.Columns.Add("likes", typeof(string));
tb.Columns.Add("message", typeof(string));

for(int i = 0; i < teams.Length; i++)
{
FBPage p = getRetrievePage(teams[i]);
FBPost t = getRetrievePosts(teams[i]);
tb.Rows.Add(p.Name, p.Picture, p.Link, p.Likes, t.Message);
}

DataList1.DataSource = tb;
DataList1.DataBind();
}

private FBPage getRetrievePage(string id)
{
Facebook_Graph_Toolkit.GraphApi.Page page = new Facebook_Graph_Toolkit.GraphApi.Page(id);
FBPage p = new FBPage();
p.Name = page.name;
p.Link = page.link;
p.Likes = page.likes;
p.Picture = page.picture;

return p;
}

private FBPost getRetrievePosts(string id)
{
Facebook_Graph_Toolkit.GraphApi.Page page = new Facebook_Graph_Toolkit.GraphApi.Page(id);
FBPost p = new FBPost();
IList<Post> posts = page.GetPosts();
p.Message = posts[0].message;

return p;
}

}
[/code]

2 thoughts on “[Facebook] 取得粉絲專頁資訊與最新一筆主題的方法 (PHP/jQuery/ASP.NET(C#))

  1. 工具:Google Search
    關鍵字:jquery
    條件:繁體中文網頁+過去 1 週+按關聯性排序+所有結果
    出現位置:第三項
    ——————————————————————
    然後就連到你的BLOG了…

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *