Hi guys,

Im just trying to figure out how to print only the last line of a file.txt and then also print all lines bar the last one. Having used linux for quite a while, these could simply be done in bash using head and tail. Is there any php command which will do the same thing? any help appreciated

thanks,

stewart

    Not without reading the rest of the file first (to see where the line breaks are and hence where the last line begins.). [man]file[/man] would be a good choice of function here.

      24 days later

      To get the top row(s) of a text file, you can use this method:

      $lines=4;
      $data="";
      $fp=fopen("file.txt", "r");
      while ($lines) {
          $data.=fgets($fp, 1024);
          $lines--;
      }
      fclose($fp);
      

      To get the end of a file, you can open the file, seek to the end, and keep seeking back and reading in lines. That way, you don't have to read the whole file to get the last X lines. Reply if you need specifics - it's not tricky 😉

        Write a Reply...