0

So I have a website where I want to display a word from a textfile. I have done my textfile where the script should read from but it shows the whole textfile :S

<?

$filename = "arraytext.txt";
$arr = file($filename);
foreach($arr as $line){
    print $line . "<br />";
}

?>

`

It shows the whole textfile at once. I just want it to show 1 row and that's the first word. What am I doing wrong?

2 Answers2

0

To read file line by line, you have to use fgets() function
Here is an example :

$file = fopen("test.txt","r");

while(! feof($file))
  {
  echo fgets($file). "<br />";
  }

fclose($file);
Akshay Vanjare
  • 655
  • 3
  • 10
0
<?
  $filename = "arraytext.txt";
  $f = fopen($filename, 'r');
  echo fgets($f);
  fclose($f);
?>

To run it every 12 hours, add this line to your "/etc/crontab" file (for example):

00 11,23 * * * root php path-to-your-script/name-of-your-script.php

UPDATE: After your comment I think I better understood your question (sorry).
Forget about "crontab" stuff...
Just do:

<?
  $filename = "arraytext.txt";
  $arr = file($filename);
  foreach ($arr as $line) {
    print $line . "<br />";
    sleep(60 * 60 * 12); // (60 * 60) * 12 seconds sums up to 12 hours
  }
?>

Be warned, though, that php run in "web" mode (as opposed to "cli" mode) has strict execution time limits (see http://php.net/manual/en/function.set-time-limit.php).
I suppose you are using this on the web interface since in your question you use the html tag <br />...

Note: sorry, but why do you want to write one line each 12 hours??? :-)

MarcoS
  • 17,323
  • 24
  • 96
  • 174
  • Awesome bro thank you. It shows me the first row. How should I make it able to read the new line every 12 hour? It could be done with cron job right? – spurrenirre Nov 03 '14 at 15:43
  • You don't need to say thank you, on SO. Just accept the most useful answer... :-) – MarcoS Nov 03 '14 at 15:44
  • So everytime this this runs it will automatically update to the next line? – spurrenirre Nov 03 '14 at 15:45
  • The cron job didn't work. It doesn't change the text to the next line :S – spurrenirre Nov 03 '14 at 16:06
  • Yeah I looked up foreach but now you wrote it. so the sleep will sleep everything until 12 hours has gone and then it will change line to the next one? Since my arraytext.txt is with
    (this comment doesnt show it)for ex First Second Third etc
    – spurrenirre Nov 03 '14 at 16:12
  • I have a site that shows the "daily" food. I want this to get updated every 12 hour so the "new" menu is out. – spurrenirre Nov 03 '14 at 16:14
  • I see. This is not the right approach to address your use case, sorry... You really should read something about AJAX (http://www.w3schools.com/ajax/)... – MarcoS Nov 03 '14 at 16:19
  • Hmm. Shouldnt there be a way to create a script that reads the second line in the arraylist.txt? So it only jumps every 12 hour. – spurrenirre Nov 03 '14 at 16:21