NameSilo

File Read [PHP]

Spaceship Spaceship
Watch

w1ww

Established Member
Impact
9
Hello,

Using the file read function

PHP:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');

How can I make it to just read the last 5 lines of the file?

Thank you
 
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
AfternicAfternic
PHP:
$file=file('testFile.php');
$lines=count($file);
$i=$lines-5;
while($i < $file){
echo $file[$i];
$i++;
}
I think that may work, it isn't checked at all though, so there may be errors
 
0
•••
lee101 said:
PHP:
$file=file('testFile.php');
$lines=count($file);
$i=$lines-5;
while($i < $file){
echo $file[$i];
$i++;
}
I think that may work, it isn't checked at all though, so there may be errors

PHP:
$file = file('file.txt');

foreach($file as $line){
   echo $line;
}

easier :p
 
0
•••
ahtum said:
easier :p
Yes, but w1ww only wants the last 5 lines, that would display all of them :)
 
0
•••
ahtum,

Thanks for your input but lee101 solution works better, although, using his code I get the text, but I get also:

PHP:
Fatal error: Maximum execution time of 30 seconds exceeded in 3.php on line 7

what is wrong?

Thank you
 
0
•••
what are lines 6-8 on 3.php, it sounds like another problem
edit:sorry, i'd wrote the code wrong, use this instead:
PHP:
 $file=file('testFile.php');
$lines=count($file);
$i=$lines-5;
while($i < $lines){
echo $file[$i];
$i++;
}
 
0
•••
It works now :)

Thank you guys!!
 
0
•••
Topic is solved but just my input:

PHP:
$file = file('testFile.php');

for($i = 0; $i <= 5; $i++)
{
    echo $file[count($file)-$i];
}

Just a little cleaner than using while :)

edit: Read below :santa:
 
Last edited:
0
•••
I know it's solved, too, but:

Matthew, that would show the lines backwards. (I think.)

PHP:
$file = file('testFile.php');

for ($i = 5; $i >= 0; $i--) {
  echo $file[count($file)-$i];
}

I don't know if that would work because count returns the number of items but that is one higher than the arrays highest key (if you can understand what I'm trying to say.) You might have to start with $i as 6 and just do $i > 0; :x
 
1
•••
Ahh good point Dan. That didn't even enter my head :)

(p.s. Your example is correct)
 
0
•••
Dynadot — .com TransferDynadot — .com Transfer

We're social

Domain Recover
DomainEasy — Zero Commission
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back