drol55885602 2013-04-07 22:15
浏览 180
已采纳

从php中的.txt文件中获取特定文本

I am having a log file like this :

2013-04-08-03-17-52: Cleaning Up all data for restart operation
2013-04-08-03-18-02: Creating new instance of app before closing
2013-04-08-03-18-03: New instance created and running
2013-04-08-03-18-03: Application started

Currently, i am loading full log file every second to show it to the user using jquery ajax, As this being soo inefficient i am trying to figure out some way to load only the updated lines from log file.

Is their any way to get lines only after a particular time stamp 2013-04-08-03-18-03 , For this i will be managing a variable with last timestamp and will be updating it every time i get new lines.

I am kind of New to Php and know only the basics of reading and writing files.

  • 写回答

3条回答 默认 最新

  • douren7179 2013-04-07 22:28
    关注

    You might want to check the file modification time first to see whether or not you need to reload the log file. You can use the filemtime-function for that.

    Furthermore, you can use the file_get_contents-function using an offset to read the file from a certain point.

    Edit: So, how does it work?

    Suppose you have stored the last modification time in a session variable $_SESSION['log_lastmod'] and the most recent offset in $_SESSION['log_offset'].

    session_start();
    
    // First, check if the variables exist. If not, create them so that the entire log is read.
    if (!isset($_SESSION['log_lastmod']) && !isset($_SESSION['log_offset'])) {
        $_SESSION['log_lastmod'] = 0;
        $_SESSION['log_offset'] = 0;
    }
    
    if (filemtime('log.txt') > $_SESSION['log_lastmod']) {
        // read file from offset
        $newcontent = file_get_contents('log.txt', NULL, NULL, $_SESSION['log_offset']);
        // set new offset (add newly read characters to last offset)
        $_SESSION['log_offset'] += strlen($newcontent);
        // set new lastmod-time
        $_SESSION['log_lastmod'] = filemtime('log.txt');
    
        // manipulate $newcontent here to what you want it to show
    } else {
        // put whatever should be returned to the client if there are no updates here
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题