drl92080 2013-05-28 16:05
浏览 28
已采纳

PHP:包含时反转/反转文件行顺序或使用fwrite写入时

I have created a small module that allows users to add small messages when entering a webpage. For that, it writes them down into a html document (msg.html) and later in the page I include() it into a div.

My biggest problem is that I don't know how to make the resultant file, the one showed with the include(), to show the most recent as first and so on... I tried changing the fopen atributes (a, r, b, c, cb+, etccccc), but nothing steady.

For how I see it, I should make the php form write into the file, append ALWAYS at the top most line, so the include() will show the file normally, the most recent as first.

OR, I could make some kind of reversed array and include() or echo the "reversed" content. In either way, I just don't have the knowledge to make that happen.

Here is my code:

<?php

if (isset($_POST['msg'])) {

    $usr = preg_replace('/[^a-zA-Z0-9]/', '',$_POST['usr']);
    $msg = $_POST['msg'];

    if (empty($usr)) {
        $usr = "Anonymous";
    }

    if (!empty($msg)) {
        $fsp = fopen('msg.html', "ab+"); 
        fwrite($fsp, '<tr><td class="info"><span class="usr">'. $usr .'</span><br><span class="dat">'. date("F j, Y, H:i ") .'</span></td><td>'. $msg ."</td></tr>
");
        fclose($fsp);
        unset($_POST['msg']);
        unset($_POST['usr']);
    }
}

?>

<form method="post" action="#">
    <div id="comments">
        <h3>Messages</h3>
        <table>
            <tr><td>Name:</td><td><input type="text" id="usr" name="usr"></td></tr>
            <tr><td>Message:</td><td><textarea id="msg" name="msg"></textarea></td></tr>
            <tr><td></td><td><input type="submit" value="Add message!"></td></tr>
        </table>

        </table>
        <table id="ccc">
            <?php include('msg.html'); ?>
        </table>
    </div>
</form>
  • 写回答

1条回答 默认 最新

  • dongsong4418 2013-05-28 16:27
    关注

    Since you are descreetly placing a newline at the end of each line you could do this instead of include:

    $arr = file('msg.html');
    echo implode("", array_reverse($arr));
    

    The only gotcha I can see here is that you will need to make sure that no newlines exist within the message itself. so change

    fwrite($fsp, '<tr><td class="info"><span class="usr">'. $usr .'</span><br><span class="dat">'. date("F j, Y, H:i ") .'</span></td><td>'. $msg ."</td></tr>
    ");
    

    to

    fwrite($fsp, '<tr><td class="info"><span class="usr">'. nl2br($usr) .'</span><br><span class="dat">'. date("F j, Y, H:i ") .'</span></td><td>'. nl2br($msg) ."</td></tr>
    ");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)