Reputation: 95
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.
My data.txt
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:
<?php
$myFile = "data.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;
?>
Upvotes: 3
Views: 3339
Reputation: 15550
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
<?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>
Upvotes: 4