Read txt from bottom to top

0

I have this simple code that reads an arch; notes.txt. The last data leaves them down and not up, that is normal for how they are saved, but how can I make them read from bottom to top.

<?php
$ar = fopen("notas.txt","r") or die("NULL");
while (!feof($ar)){
  $linea = fgets($ar);
  $lineasalto = nl2br($linea);
  echo $lineasalto;
}
fclose($ar);
?>
    
asked by Stn 06.11.2018 в 05:32
source

2 answers

1

You can read all the lines of the file and save them in an array with

$lineas = file("notas.txt", FILE_IGNORE_NEW_LINES);

Then you can invert the array with array_reverse or you can traverse it in a for loop from the last position to the start.

<?php
$lineas = file("notas.txt", FILE_IGNORE_NEW_LINES);
$numElementos = count($lineas) - 1;

for ($i = $numElementos; $i >= 0; $i--) {
   echo nl2br($lineas[$i]);
}
    
answered by 06.11.2018 / 12:31
source
0

You can use the tac command or save the elements previously in an array and use reverse order to traverse them in an inverse way

$myfile = 'myfile.txt';
$command = "tac $myfile > /tmp/myfilereversed.txt";

link

    
answered by 06.11.2018 в 07:07