您需要閱讀無限循環中的文件內容while(true)
。我會通過代碼評論來解釋。
// 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);
}
}
要進行測試,打開一個終端窗口,併發出:
while true; do echo `date` >> log.txt; sleep 1; done
這將當前日期時間字符串追加到每個單獨第二的文件。現在打開另一個終端併發出php read.php
以查看是否正在實時讀取文件。它會輸出這樣的事情:
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...
如果你傾向於通過HTTP服務這一點,你需要打印讀取緩衝區後添加ob_flush()
電話:
// While not reached the end of the file
while (! feof($fp)) {
print fgets($fp) . '<br>';
// Flush the output cache
ob_flush();
}