[PHP]PO3 一次幫你從3個地方(Buboo,Plurk,Twitter)讀取訊息!
為了統一來源及安全限制,我在server端放一個ajax.php用來取得Buboo,Plurk,Twitter的json資料,在client使用javascript處理資料呈現。
資料來源及內容:
Buboo [資料來源] : http://api.buboo.tw/user_timeline/{使用者帳號}.rss?count={訊息數量}
created_at : 日期(2008-07-07 23:15)
text : 訊息內容
id : 訊息代號(8f8170289cba351)
原文網址:http://buboo.tw/msg/{id}.html
Plurk [資料來源] : 無直接網址。
需先取的userid(數字),再POST到 http://www.plurk.com/TimeLine/getPlurks ,其中欄位 user_id=$userid
qualifier : 動作(”:”表示未指定)
content_raw : 訊息內容
content : 訊息內容(已格式成HTML)
posted : 日期(new Date("Mon, 07 Jul 2008 04:08:40 GMT"))
原文網址:無
Twitter [資料來源] : http://twitter.com/statuses/user_timeline/{使用者帳號}.json&count={訊息數量}
text : 訊息內容
Source : 發訊來源
id : 訊息代號(851703528)
created_at : 日期(Mon Jul 07 04:08:41 +0000 2008)
原文網址:http://twitter.com/{user.screen_name}/statuses/{id}
Server端 ajax.php:
<?php
# 設定傳入參數改以 p_ 開頭變數表示
import_request_variables('gp', 'p_');
if ( $p_type=="plurk" ) {
// plurk 特別處理
echo get_plurk($p_username);
} // if
else {
// 一般指定url
echo file_get_contents($p_url, 1000000);
} // else
// 取得plurk資料
function get_plurk($uid) {
if ( $uid=="" ) return "";
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
// 先從網頁解析出user_id
curl_setopt($curl_handle, CURLOPT_URL, "http://www.plurk.com/user/$uid");
$html = curl_exec($curl_handle);
preg_match('/var GLOBAL = \{.*"uid": ([\d]+),.*\}/imU', $html, $matches);
$uid = $matches[1];
if ( $uid == '' )
$json = "No User";
else {
// 用POST送出請求
curl_setopt($curl_handle, CURLOPT_URL, 'http://www.plurk.com/TimeLine/getPlurks');
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "user_id=$uid");
$json = curl_exec($curl_handle);
} // else
curl_close($curl_handle);
return $json;
}
?>
Client端 javascript:
AJAX (prototype)
function ajaxBuboo() {
var uid = $('userid').value;
$('divBuboo').innerHTML = "loading ("+uid +")...";
var url = 'ajax.php?url=http://api.buboo.tw/user_timeline.json?uid='+uid +'&count=5';
new Ajax.Request(url,
{
method: 'get',
asynchronous: true,
onSuccess:showResultBuboo,
onFailure:ShowFailure
}
);
}
function showResultBuboo(httpObj) {
$('divBuboo').innerHTML = buboo(httpObj.responseText.evalJSON(false));
}
Buboo
function buboo(json) {
var retHtml = "";
for (var i=0; i<json.length && i<<?=$count?>; i++){
retHtml += ('<li>'+json[i].text+' <a href="http://buboo.tw/msg/'+
json[i].id+'.html" target="_blank">url</a></li>'
);
} // for
return retHtml;
}
Plurk
function plurk(json) {
var retHtml = "";
for (var i=0; i<json.length ; i++){
retHtml += ('<li>'+
(json[i].qualifier==":"?"":json[i].qualifier+":" )+' '+
json[i].content+' ['+json[i].response_count+']</li>'
);
} // for
return retHtml;
}
function twitter(json) {
var retHtml = "";
var username = "";
for (var i=0; i<json.length; i++){
retHtml += ('<li>'+json[i].text+' <a href="http://twitter.com/'+
json[i].user.screen_name+'/statuses/'+json[i].id+'" target="_blank">url</a></li>'
);
} // for
return retHtml;
}