繁体   English   中英

每分钟从文本文件中获取数据并更新网页

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM