The problem with you code is that count($file)
is not doing what you think. $file
is just a file handle resource, not an array. You end up comparing $i >= -11
, which will of course always evaluate to true
/
You might try something like this if you want to just use linux to grab the last ten lines (not sure if you are on linux):
$initial_csv = 'csvfile.txt';
$truncated_csv ='csvfile_trun';
$number_of_lines_from_end = 10;
shell_exec('tail -n ' . $number_of_lines_from_end . ' ' . $initial_csv . ' > ' . $truncated_csv);
$file=fopen($truncated_csv,"r");
$pagelist=array();
$i=0;
while (!feof($file)) {
$pagelist[$i]=fgetcsv($file);
$i++;
}
fclose($file)
Alternatively, if you don't mind having the entire file in memory (i.e. the file will remain small), you can read the entire file into an array like this.
$csv = 'csvfile.txt';
$number_of_lines_from_end = 10;
$file_array = file($csv);
$line_count = count($file_array);
$start = $line_count - $number_of_lines_from_end - 1;
$pagelist=array();
for ($i = $start; $i < $line_count; $i++) {
$pagelist[]=fgetcsv($file);
}