[英]get specific text from .txt file in php
我有一個這樣的日志文件:
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
目前,我每秒加載完整的日志文件,使用jquery ajax向用戶顯示,因為這樣效率太低,我試圖想辦法從日志文件中加載只更新的行。
他們是否只能在特定的時間戳之后獲取線路2013-04-08-03-18-03
,為此我將管理一個帶有上一個時間戳的變量,並且每次我獲得新線路時都會更新它。
我是Php的新手,只知道閱讀和編寫文件的基礎知識。
您可能希望首先檢查文件修改時間,以查看是否需要重新加載日志文件。 您可以使用filemtime
。
此外,您可以使用file_get_contents
-function使用偏移量從某個點讀取文件。
編輯 :那么,它是如何工作的?
假設您已將最后修改時間存儲在會話變量$_SESSION['log_lastmod']
,並將最近的偏移量存儲在$_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
}
你可以試試
session_start();
if (! isset($_SESSION['log'])) {
$log = new stdClass();
$log->timestamp = "2013-04-08-03-18-03";
$log->position = 0;
$log->max = 2;
$_SESSION['log'] = &$log;
} else {
$log = &$_SESSION['log'];
}
$format = "Y-m-d-:g:i:s";
$filename = "log.txt";
// Get last date
$dateLast = DateTime::createFromFormat($format, $log->timestamp);
$fp = fopen($filename, "r");
fseek($fp, $log->position); // prevent loading all file to memory
$output = array();
$i = 0;
while ( $i < $log->max && ! feof($fp) ) {
$content = fgets($fp);
// Check if date is current
if (DateTime::createFromFormat($format, $log->timestamp) < $dateLast)
continue;
$log->position = ftell($fp); // save current position
$log->timestamp = strstr($content, ":", true); // save curren time;
$output[] = $content;
$i ++;
}
fclose($fp);
echo json_encode($output); // send to ajax
嘗試這樣的事情:
<?php
session_start();
$lines = file(/*Insert logfile path here*/);
if(isset($_SESSION["last_date_stamp"])){
$new_lines = array();
foreach($lines as $line){
// If the date stamp is newer than the session variable, add it to $new_lines
}
$returnLines = array_reverse($newLines); // the reverse is to put the lines in the right order
} else {
$returnLines = $lines;
}
$_SESSION['last_date_stamp'] = /* Insert the most recent date stamp here */;
// return the $returnLines variable
?>
這樣做是逐行讀取文件,如果會話變量已經存在,則將日期戳比會話變量中的行更新的所有行添加到返回變量$returnLines
,如果不存在會話變量的話將所有行放在$returnLines
中的文件中。
在此之后,create.updates會話變量以供下次執行代碼時使用。 最后,它使用$returnLines
變量返回日志文件數據。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.