为什么Twitter api调用这么慢?

时间:2011-01-14 11:53:30

标签: php performance twitter

当我执行以下代码时,需要10-12秒才能响应。

Twitter或我们的服务器存在问题吗?

我真的需要知道,因为这是在我们的网站上显示推文的代码的一部分,12秒的加载时间是不可接受的!

function get_latest_tweets($username)
  {
    print "<font color=red>**". time()."**</font><br>";
    $path = 'http://api.twitter.com/1/statuses/user_timeline/' . $username.'.json?include_rts=true&count=2';
    $jason = file_get_contents($path);
    print "<font color=red>**". time()."**</font><br>";
  }

由于

2 个答案:

答案 0 :(得分:1)

当您将URL放入浏览器时(http://api.twitter.com/1/statuses/user_timeline/username.json?include_rts=true&count=2)多长时间页面出现需要吗?如果它很快,那么您需要在服务器上开始搜索。

答案 1 :(得分:1)

使用curl而不是file_get_contents()来请求,以便压缩响应。这是我使用的卷曲功能。

function curl_file_get_contents($url)
{
    $curl = curl_init();

    curl_setopt($curl,CURLOPT_URL,$url); //The URL to fetch. This can also be set when initializing a session with curl_init().
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE); //TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
    curl_setopt($curl,CURLOPT_ENCODING , "gzip");

    curl_setopt($curl, CURLOPT_FAILONERROR, TRUE); //To fail silently if the HTTP code returned is greater than or equal to 400.
    curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);

    $contents = curl_exec($curl);
    curl_close($curl);

    return $contents;
}