我一直在努力为自己创建一个快速的 twitter 小部件以供自己重复使用,它只是一些简单的东西,它可以缓存来自公共 api 的数据。由于 twitter 只允许某个时间段内的 X 请求,并且我一直在共享主机上对此进行测试,因此我经常用完请求并且 twitter 拒绝我的请求。因此,在写入更新的缓存文件之前,我首先检查我的请求是否被拒绝。
不幸的是,我似乎不时丢失此文件,因为我经常看到“临时文件未写入”消息。只有当文件不存在时才会出现。
这是完整的php函数:
function getTweets($num)
{
$cfile = sys_get_temp_dir().'/e1z'. $type . md5 ( 'something' );
if (is_file ( $cfile ) == false) {
$cfile_time = strtotime ( '1983-04-30 07:15:00' );
} else {
$cfile_time = filemtime ( $cfile );
}
$difference = strtotime ( date ( 'Y-m-d H:i:s' ) ) - $cfile_time;
if ($difference >= 100) {
$tags = array("created_at", "text", "screen_name", "profile_image_url"); // twitter names
$local = array("time", "msg", "user", "image"); // local names
$reader = new XMLReader();
$url = 'http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=boriskourt&include_rts=true&count=' . $num;
$headers = get_headers($url, 1);
if ($headers[0] == 'HTTP/1.0 400 Bad Request'){
if (is_file ( $cfile ) == true) {
$returner = file_get_contents ( $cfile );
touch ( $cfile );
file_put_contents ( $cfile, strval($returner) );
$returner = file_get_contents ( $cfile );
return $returner;
} else {
$returner = "<li><span>Temp file not written</span></li>";
return $returner;
}
} else {
$reader->open($url);
$i = 0;
$k = 1;
while ($i < $num)
{
$j = 0;
while ($reader->read() && $j < 4) // run through each tweet
{
if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == $tags[$j])
{
while ($reader->read())
{
if ($reader->nodeType == XMLReader::TEXT && $j == 0)
{
if ($k) {
$tweets[$i][$local[$j]] = $reader->value;
$j++;
$k=0;}
else {$k=1;}
break;
}
else if ($reader->nodeType == XMLReader::TEXT)
{
$tweets[$i][$local[$j]] = $reader->value;
$j++;
break;
}
}
}
}
$i++;
}
$returner = "";
foreach ($tweets as $value) {
if ($value[user] != 'fugataquintet') {
$returner .= '<li class="retweet">';
} else {
$returner .= '<li>';
}
$messager = $value[msg];
$messager = " ".preg_replace( "/(([[:alnum:]]+:\/\/)|www\.)([^[:space:]]*)"."([[:alnum:]#?\/&=])/i", "<a href=\"\\1\\3\\4\" target=\"_blank\">"."\\1\\3\\4</a>", $messager);
$messager = preg_replace( "/ +@([a-z0-9_]*) ?/i", " <a href=\"http://twitter.com/#!/\\1\" target=\"_blank\">@\\1</a> ", $messager);
$messager = preg_replace( "/ +#([a-z0-9_]*) ?/i", " <a href=\"http://twitter.com/search?q=%23\\1\" target=\"_blank\">#\\1</a> ", $messager);
$returner .= '<span>'.$messager.'</span><a class="datereplace" href="http://twitter.com/#!/fugataquintet" title="'.$value[time].'">'.$value[time].'</a></li>';
}
touch ( $cfile );
file_put_contents ( $cfile, strval($returner) );
return $returner;
}
} else {
$returner = file_get_contents ( $cfile );
return $returner;
}
}