首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >聊天系统日志问题

聊天系统日志问题
EN

Stack Overflow用户
提问于 2014-12-15 04:49:25
回答 1查看 100关注 0票数 0

我已经用jquery、php和ajax制作了一个聊天系统,我想让聊天窗口显示html日志的最后10行。

log.html如下所示:

代码语言:javascript
复制
<div class='msgln'><b>Brian</b>: dd<br></div><div class='msgln'><b>Brian</b>: ddf<br></div><div class='msgln'><b>Arne</b>: PIS!<br></div><div class='msgln'><b>Brian</b>: sdfsdf sdfsdffds sdfdsf sdf sdf  dfs dfsdf sdf sfd  sfd  fsd fsd sdf  sdffsd sd fsdfsd fsd fsd<br></div><div class='msgln'><i>Brian er kommet på chatten.</i><br></div>

我的php现在看起来像这样:

代码语言:javascript
复制
echo "<div id='chatbox'>";
if(file_exists("log.html") && filesize("log.html") > 0){
$handle = fopen("log.html", "r");
$contents = fread($handle, filesize("log.html"));

fclose($handle);

$lastfifteenlines = array_slice(explode("<br>",file_get_contents($contents)),-10);

echo $lastfifteenlines;
}
echo "</div>";

但它显示了日志中的所有内容...

我怎么才能只显示最后10行?br发生的最后10次?

编辑:

ajax和jquery:

代码语言:javascript
复制
function loadLog(){     
var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20; //Scroll height before the request
$.ajax({
url: "log.html",
cache: false,
success: function(html){        
$("#chatbox").html(html); //Insert chat log into the #chatbox div   

//Auto-scroll           
var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20; //Scroll height after the request
if(newscrollHeight > oldscrollHeight){
$("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
}               
},
});
}
EN

回答 1

Stack Overflow用户

发布于 2014-12-15 04:58:10

代码语言:javascript
复制
function get_last_lines($fp, $num)
{
    $idx   = 0;

    $lines = array();
    while(($line = fgets($fp)))
    {
        $lines[$idx] = $line;
        $idx = ($idx + 1) % $num;
    }

    $p1 = array_slice($lines,    $idx);
    $p2 = array_slice($lines, 0, $idx);
    $ordered_lines = array_merge($p1, $p2);

    return $ordered_lines;
}

// Open the file and read the last 15 lines
$fp    = fopen('log.html', 'r');
$lines = get_last_lines($fp, 15);
fclose($fp);

// Output array
print_r($lines);

你自己试试吧。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27473929

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档