Dynadot Aftermarket: discover domain gems worth investing in. Visit our aftermarket.

File Read [PHP]

SpaceshipSpaceship
SpaceshipSpaceship
SpaceshipSpaceship
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
Close
The views expressed on this page by users and staff are their own, not those of NamePros.
GoDaddyGoDaddy
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
Close
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
Close
ahtum said:
easier :p
Yes, but w1ww only wants the last 5 lines, that would display all of them :)
 
0
Close
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
Close
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
Close
It works now :)

Thank you guys!!
 
0
Close
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
Close
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
Close
Ahh good point Dan. That didn't even enter my head :)

(p.s. Your example is correct)
 
0
Close
DomainEasy: flexible LTO options. Close more domain deals with financing.

We're social

Escrow.com
Spaceship
Domain Recover
CryptoExchange.com

NamePros updates

Switch between accounts
You can now stay logged in to more than one NamePros account in the same browser. Click your avatar, then "Accounts in this browser", to...
AIVikings
Catchy
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back