user3226468 user3226468 - 1 year ago 114
PHP Question

fetch data from text file and update web page every minute

I have a text file storing strings. The text file will be changing every 1 minute. I want to show whole string in my php page.
My php code just fetchs the data from text file. I want my php page to refresh every minute and show the updated data.


file is:

1~1~10,56,82,34,22,78,56,15,41,25,47,33,48~82-I am Aakash,83- I am Vijay

my php code for fetching data is:

$myFile = "data.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
echo $theData;

Answer Source

You can use stream_get_contents. Simply, stream your text file like tailing. Your client html will make ajax call every minute to your server side script written in php. For example;

PHP: file_read.php

if (isset($_GET['tail'])) {
  $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);


<!doctype html>
<html lang="en">
  <meta charset="UTF-8">
  <script src="jquery.min.js"></script><!-- give corrected jquery path -->
  setInterval(function(){get_contents();}, 10000*60);
  function get_contents() {
    $.get('file_read.php.php?tail', function(data) {
  <div id="contents">Loading...</div>