最近參加中華電信加值應用大賽,作品網站其中一個賣點就是結合Twitter API,在這分享一下如何用PEAR的Services_Twitter套件,來撰寫Twitter API。
1.當然就是打開終端機,安裝Services_Twitter套件(注意相依套件)pear install Services_Twitter-0.3.0
2.發送訊息,好友訊息範例<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Twitter API</title>
<style>
.item {
float:none;
clear:both;
margin-top:1em;
}
.img {
float:left;
margin-right:1em;
padding-bottom: 10px;
height: 48px;
width: 48px;
}
small {color:#aaaaaa;}
</style>
</head>
<body>
<div>
<b>What are you doing?</b>
</div>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF'])?>" method="post">
<input type="text" name="status" id="status" maxlength="140" /><br />
<input type="submit" name="submit" value="送出" />
</form>
<?php
// include class
include_once 'Services/Twitter.php';
if (isset($_POST['submit'])) {
try { //發送訊息
//接收表單status訊息
$status = $_POST['status'];
// initialize service object
$service = new Services_Twitter($user, $pass);
// update status 更新訊息
$service->statuses->update($status);
// perform logout 登出
$service->account->end_session();
} catch (Exception $e) {
//錯誤訊息
die('ERROR: ' . $e->getMessage());
}
}
try { //顯示自已與following的好友訊息
// initialize service object
$service = new Services_Twitter($user, $pass);
//顯示自已與following的好友訊息
$count=array('count'=>'10');//顯示訊息數10筆
$response = $service->statuses->friends_timeline($count);
if (count($response->status) > 0) {
echo ' <div>
<b>好友訊息</b>
</div><ul>';
foreach ($response->status as $status) {
echo '<div class="item"><img src="' . $status->user->profile_image_url . '" class="img" />';
echo '<a href="">' . $status->user->screen_name . '</a> '. $status->text . '<br/>';
echo '<small>' . $status->created_at . '</small>';
}
}
echo '</ul>';
// perform logout
$service->account->end_session();
} catch (Exception $e) {
die('ERROR: ' . $e->getMessage());
}
?>
</body>
</html>
範例成果
相關文章:
Using-the-Twitter-API-with-PHP-and-PEAR