[PHP]twitter APIを使用して、検索した結果を出力する

twitterに書き込まれたツイートを、PHPで検索して出力させるプログラムです。

    $keyword = urlencode( 'キーワード' );
 
    //--------------------------------
    // twitter APIを使用して検索を行う
    //--------------------------------
    $result = file_get_contents( 'http://search.twitter.com/search.atom?q='. $keyword );
    $xml = new SimpleXMLElement( $result );
 
    if ( $xml != NULL && $xml->entry != NULL ) {
        $str = "";
 
        //----------------------------------
        // 全検索結果を処理するまで繰り返し
        //----------------------------------
        foreach($xml -> entry as $item) {
 
            //----------------------------------
            // 印字データを取得
            //----------------------------------
            $published = $item->published;
            $title     = $item->title;
            $userUrl   = $item->author->uri;
            $userName  = $item->author->name;
 
            //----------------------------------
            // 取得データをhtmlに変換
            //----------------------------------
            $str .= $title . '<br />';
            $str .= '<span style="color:#ccc;font-size:8pt"> by <a href="' . $userUrl . '">' . $userName . '</a> ';
            $str .= '<br />at ' . $published . '</span>';
            $str .= '<hr />';
        }
    }   
 
    //----------------------------------
    // 取得結果を表示する
    //----------------------------------
    echo $str;



http://search.twitter.com/search.atomのURLより検索を行います。

検索結果は、atom形式のxmlで返されるので、SimpleXMLを使用してデータの取得をを行い、htmlに変換して上で出力を行っています。

関連記事

コメントを残す

メールアドレスが公開されることはありません。