T

twitter

で、今時twitterを使ってみる。仕事中でも簡単に観られるように、登録した人たちのセリフだけXMLで引っ張ってみた。XMLの加工はまた今度。他の機能は必要に応じて追加しよう。

<?php

$user = 'hogehoge';
$pass = 'hogehoge';

define('_TWITTER_SERVER', 'twitter.com');

class twitter{

    function __construct(){

    }
    
    function setUser($user){
        if(!$user){
            die("NO USERNAME SUPPLIED.\\n");
        }
        $this->user = $user;
    }
    
    function setPass($pass){
        if(!$pass){
            die("NO PASSWORD SUPPLIED.\\n");
        }
        $this->pass = $pass;
    }
    
    function connect(){
        return $this->_connect2Twitter();
    }
    
    function _connect2Twitter(){
        if($this->con === NULL){
            $this->con = @fsockopen(_TWITTER_SERVER, 80, $errno, $errstr, 30);
            if(!$this->con){
                die($errno . ":" . $errstr . "\\n");
            }
        }
        return $this->con;
    }
    
    function disconnect(){
        fclose($this->con);
    }
    
    function getFriendsTimelineXML(){
        if($this->connect()){
            $basic = base64_encode($this->user . ":" . $this->pass);
            $req = "GET /statuses/friends_timeline/" . $this->user . ".xml HTTP/1.0\\r\\n";
            $req .= "Host:" . _TWITTER_SERVER . "\\r\\n";
            $req .= "Authorization: Basic " . $basic . "\\r\\n\\r\\n";
            fputs($this->con, $req);
            $content = '';
            do{
                $data = fgets($this->con, 1024);
                if(strlen($data) == 0){
                    break;
                }
                $data = preg_replace_callback("/((?:&#)([\\d]+)(?:;))/", 
                    array($this, '_code2Char'), $data);
                $content .= $data;
            }while(true);
            $data_ar = split("\\r\\n\\r\\n", $content, 2);
            return $data_ar[1];
        }else{
            $content = "Connection Failed.";
            return $content;
        }
    }
    
    function _code2Char($array){
        $val = $array[2];
        return mb_convert_encoding(pack("H*", dechex($val)), "UTF-8", "UCS-2");
    }
    
}
$obj = new twitter();
$obj->setUser($user);
$obj->setPass($pass);
$obj->connect();
print($obj->getFriendsTimelineXML());
$obj->disconnect();

?>

_code2Charだけ必死だな。

Posted by on 6月 13, 2007 in PHP

コメントを残す