2016-12-28 8 views
1

私は、データをPHPファイルに書き出しているログファイルを持っています。これは、そのためのコードです:更新ログファイルからリアルタイムで1行ずつ読み込みます。

$filename='/var/log/siawa/dashboard/iot.log'; 

$source_file = fopen($filename, "r") or die("Couldn't open $filename"); 

while (!feof($source_file)) { 
    $buffer = fgets($source_file, 4096); // use a buffer of 4KB 
    $buffer = str_replace($old,$new,$buffer); 
    echo $buffer. "<br />" . "\n"; 
} 

これが働いているが、私はその元のログファイルに書き込まれます後は、10秒ごとに発言した後、PHPのログデータを更新します。どうやってするか。

答えて

2

無限while(true)ループでファイルの内容を読む必要があります。私はコードコメントを通して説明します。

while true; do echo `date` >> log.txt; sleep 1; done 

これは、それぞれ単一の第2のためのファイルに現在の日時文字列を追加します:、これをテストターミナルウィンドウと、問題を開くには

// read.php 
<?php 

// Last read position 
$last = 0; 

// Path to the updating log file 
$file = 'log.txt'; 

while (true) { 
    // PHP caches file information in order to provide faster 
    // performance; In order to read the new filesize, we need 
    // to flush this cache. 
    clearstatcache(false, $file); 

    // Get the current size of file 
    $current = filesize($file); 

    // Reseted the file? 
    if ($current < $last) { 
     $last = $current; 
    } 
    // If there's new content in the file 
    elseif ($current > $last) { 
     // Open the file in read mode 
     $fp = fopen($file, 'r'); 

     // Set the file position indicator to the last position 
     fseek($fp, $last); 

     // While not reached the end of the file 
     while (! feof($fp)) { 
      // Read a line and print 
      print fgets($fp); 
     } 

     // Store the current position of the file for the next pass 
     $last = ftell($fp); 

     // Close the file pointer 
     fclose($fp); 
    } 
} 

。今すぐ別の端末を開き、ファイルがリアルタイムで読み込まれているかどうかを確認するためにphp read.phpを発行してください。あなたはHTTPを介してこのサービスを提供する傾向がある場合は、読み取りバッファを印刷した後ob_flush()呼び出しを追加する必要があります

Wed Dec 28 18:01:12 IRST 2016 
Wed Dec 28 18:01:13 IRST 2016 
Wed Dec 28 18:01:14 IRST 2016 
Wed Dec 28 18:01:15 IRST 2016 
Wed Dec 28 18:01:16 IRST 2016 
Wed Dec 28 18:01:17 IRST 2016 
Wed Dec 28 18:01:18 IRST 2016 
# Keeps updating... 

// While not reached the end of the file 
while (! feof($fp)) { 
    print fgets($fp) . '<br>'; 

    // Flush the output cache 
    ob_flush(); 
} 
これは、出力は次のようになります
関連する問題