Skip to content Skip to sidebar Skip to footer

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 wa

Solution 1:

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

<?phpif (isset($_GET['tail'])) {
  session_start();
  $handle = fopen('your_txt_file.txt', 'r');// I assume, a.txt is in the same path with file_read.phpif (isset($_SESSION['offset'])) {
    $data = stream_get_contents($handle, -1, $_SESSION['offset']);// Second parameter is the size of text you will read on each requestecho nl2br($data);
  } else {
    fseek($handle, 0, SEEK_END);
    $_SESSION['offset'] = ftell($handle);
  } 
  exit();
} 
?>

HTML:

<!doctype html><htmllang="en"><head><metacharset="UTF-8"><scriptsrc="jquery.min.js"></script><!-- give corrected jquery path --><script>setInterval(function(){get_contents();}, 10000*60);
  functionget_contents() {
    $.get('file_read.php.php?tail', function(data) {
        $('#contents').append(data);
      });
  }
  </script></head><body><divid="contents">Loading...</div></body></html>

Post a Comment for "Fetch Data From Text File And Update Web Page Every Minute"