Archive for August 29th, 2009

集成Twitter到你的网站

如果你常用Twitter,想把tweets显示在你的网站或者Blog上,该怎么办?最简单的方式是用Twitter官方的一个JavaScript,可由于功夫网的缘故,在中国的用户无法使用它,如果你有自己的网站或者Blog,且位于墙外,下面的一段PHP代码可以达到你的目的:

// 读取Twitter的函数
function twitter_process($url)
{
    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_USERAGENT, 'super_man');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

    $response = curl_exec($ch);
    $response_info = curl_getinfo($ch);
    curl_close($ch);

    switch(intval($response_info['http_code']))
    {
        case 200:
        $json = json_decode($response);
        if ($json)
        return $json;
            return $response;
        case 401:
        default:
        // NOOP
    }
}

// 显示tweets在你的网站
$o = twitter_process("http://twitter.com/statuses/user_timeline/charry.json?count=5");

for ($i = 0; $i < count($o); $i++)
{
    $item = $o[$i];

    echo "<li>";
    echo $item->{‘text’};
    echo " – ".$item->{‘created_at’};
    echo "</li>";
}

[ad]

Switch to our mobile site