1月 30
今日はphpでtwitterに呟く方法を書く。
twitterはapiで呟けるが、phpにはpearに(Services/Twitter.php)という便利なモジュールがあるので、
今回はそれを使う。細かい使い方はココが詳しい。
まずは.pearの"Services/Twitter.php"が無いと話にならない。インストール。
pear install --alldeps -f http://labs.transrain.net/files/Services_Twitter-0.4.0.tgz
以下は呟くときのサンプルソース。ID,Password,呟きたい内容を引数に渡せば勝手に呟いてくれる関数だ。
140文字を超えている場合は135文字に切って「...」をつけてくれる。
*phpインストール時に"--enable-mbstring"オプションがないと、140文字の部分が動かないかも。
public static function tweet($id = null , $pass = null , $tweet )
{
//ServicesTwitterの読み込み。
require_once "Services/Twitter.php";
//140文字を超えていたら、135文字で切って...をつける。
if(mb_strlen($tweet)> 140 )
{
$tweet = mb_substr( $tweet , 0 , 135 );
$tweet .= "... ";
}
$st =& new Services_Twitter( $id , $pass );
$st->setUpdate($tweet);
}
あとは、呼び出し側で、
self::tweet("morinoyume" , "morinoyume" , "森の夢だよーん")
とでもやれば、morinoyumeアカウントに呟かれるだろう。
twitterのAPI簡単だね。もっと勉強していきます!



