我最近遇到了一个非常相似的问题。我的大部分推特请求都使用 Remy Sharp 的这个脚本:http://remysharp.com/2007/05/18/add-twitter-to-your-blog-step-by-step/
您需要了解的是,api 超时是针对每个 IP 地址的。因此,如果 api 根据您的测试为您超时,它不会为其他 IP 地址上的其他人超时。现在,如果有人在公司或企业内部访问该网站,而同一地点的其他人也在这样做,那么超时几乎会立即发生。
要解决此问题,您需要缓存结果。我这样做的方式如下。
我使用以下代码创建了一个 twitter 缓存系统:
$twitter_username = "tadywankenobi"; //
$number_of_tweets = "10";
$options[CURLOPT_URL] = 'http://api.twitter.com/1/statuses/user_timeline.xml?screen_name='.$twitter_username.'&count='.$number_of_tweets.'&include_rts=1';
$options[CURLOPT_PORT] = 80;
$options[CURLOPT_FOLLOWLOCATION] = true;
$options[CURLOPT_RETURNTRANSFER] = true;
$options[CURLOPT_TIMEOUT] = 60;
$tweets = cache($options);
$twxml = new SimpleXMLElement($tweets);
echo "<ul>";
for($i=0;$i<=($number_of_tweets-1);$i++){
$text = $twxml->status[$i]->text;
echo "<li>".auto_link_twitter($text)."</li>";
}
echo "</ul>";
function cache($options) {
$cache_filename = "/var/cache/tweets.xml";
if(!file_exists($cache_filename)){
$handle = fopen($cache_filename, 'w') or die('Cannot open file: '.$my_file);
fclose($handle);
}// Check if cache file exists and if not, create it
$time_expire = filectime($cache_filename) + 60*60; // Expire Time (1 hour) // Comment for first run
// Set time to check file against
if(filectime($cache_filename) >= $time_expire || filesize($cache_filename) == 0) {
// File is too old or empty, refresh cache
$curl = curl_init();
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
curl_close($curl);
if($response){
file_put_contents($cache_filename, $response);
}
else{
unlink($cache_filename);
}
}else{
$response = file_get_contents($cache_filename);
}
return $response;
}
最后缓存函数所做的是在服务器上创建一个文件并将 twitter xml 反馈存储在其中。然后系统检查该文件的年龄,如果它小于一个小时,它会从那里获取结果。否则,它会重新访问 Twitter。您需要在 /var/cache 文件夹中具有可写文件(如果不存在则创建它)。
我对这段代码做了一些修改,所以如果您遇到任何问题,请告诉我。它还使用 auto_link_twitter() 函数,该函数创建 twitter 文本中所需的链接。这不是我写的,所以我现在会尝试为您找到它的链接。
希望对大家有所帮助,
T
更新:我不记得我在哪里得到了 auto_link_twitter() 函数,所以就在这里。如果写这篇文章的人看到了这篇文章,我很抱歉,我再也找不到出处了。
function auto_link_twitter($text) {
// properly formatted URLs
$urls = "/(((http[s]?:\/\/)|(www\.))?(([a-z][-a-z0-9]+\.)?[a-z][-a-z0-9]+\.[a-z]+(\.[a-z]{2,2})?)\/?[a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1})/is";
$text = preg_replace($urls, " <a href='$1'>$1</a>", $text);
// URLs without protocols
$text = preg_replace("/href=\"www/", "href=\"http://www", $text);
// Twitter usernames
$twitter = "/@([A-Za-z0-9_]+)/is";
$text = preg_replace ($twitter, " <a href='http://twitter.com/$1'>@$1</a>", $text);
// Twitter hashtags
$hashtag = "/#([A-Aa-z0-9_-]+)/is";
$text = preg_replace ($hashtag, " <a href='http://twitter.com/#!/search?q=%23$1'>#$1</a>", $text);
return $text;
}