dongpa2000 2011-08-17 10:13
浏览 53
已采纳

在PHP中删除行? 这可能吗?

I have been struggling to create a Simple ( really simple ) chat system for my website as my knowledge on Javascripting/AJAX are Limited after gather resources and help from many kind people I was able to create my simple chat system but left with one problem.

The messages are posted to a file called "msg.html" in this format : <p><span id="name">$name</span><span id="Msg">$message</span></p> And then using PHP and AJAX I will retrieve the messages instantly from the file using the file(); function and a foreach(){} loop withing PHP here is the code :

    <?php 
$file = 'msg.html';
$data = file($file);
$max_lines = 20;
if(count($data) > $max_lines){
    // here i want the data to be deleted from oldest until i only have 20 messages left.
}
foreach($data as $line_num => $line){
echo $line_num . " . " . $line; 
}
?>

My Question is how can i delete the oldest messages so that i am only left with the latest 20 Messages ?

  • 写回答

3条回答 默认 最新

  • duanlinma5885 2011-08-17 10:22
    关注

    How does something like this seem to you:

    $file = 'msg.html';
    $data = file($file);
    $max_lines = 20;
    foreach($data as $line_num => $line)
    {
        if ($line_num < $max_lines)
        {
            echo $line_num . " . " . $line; 
        }
        else
        {
            unset($data[$line_num]);
        }
    }
    file_put_contents('msg.html', $data);
    ?>
    

    http://www.php.net/manual/en/function.file-put-contents.php for more info :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?