[英]fetch data from text file and update web page every minute
我有一個存儲字符串的文本文件。 文本文件每1分鍾更改一次。 我想在我的php頁面中顯示整個字符串。 我的PHP代碼只是從文本文件中獲取數據。 我希望我的php頁面每分鍾都刷新並顯示更新的數據。
我的data.txt
文件是:
1~1~10,56,82,34,22,78,56,15,41,25,47,33,48~82-I am Aakash,83- I am Vijay
我獲取數據的PHP代碼是:
<?php
$myFile = "data.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;
?>
您可以使用stream_get_contents 。 簡單地說,像拖尾一樣流式傳輸文本文件。 你的客戶端html將每分鍾調用一次用php編寫的服務器端腳本的ajax調用。 例如;
PHP: file_read.php
<?php
if (isset($_GET['tail'])) {
session_start();
$handle = fopen('your_txt_file.txt', 'r');// I assume, a.txt is in the same path with file_read.php
if (isset($_SESSION['offset'])) {
$data = stream_get_contents($handle, -1, $_SESSION['offset']);// Second parameter is the size of text you will read on each request
echo nl2br($data);
} else {
fseek($handle, 0, SEEK_END);
$_SESSION['offset'] = ftell($handle);
}
exit();
}
?>
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="jquery.min.js"></script><!-- give corrected jquery path -->
<script>
setInterval(function(){get_contents();}, 10000*60);
function get_contents() {
$.get('file_read.php.php?tail', function(data) {
$('#contents').append(data);
});
}
</script>
</head>
<body>
<div id="contents">Loading...</div>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.