聊天系统日志问题

时间:2014-12-14 20:49:25

标签: php jquery

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

log.html看起来像这样:

<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现在看起来像这样:

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:

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
}               
},
});
}

1 个答案:

答案 0 :(得分:0)

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);

亲自试试。