Page 1 of 1

Read Last Line

Posted: Thu Jun 07, 2007 10:33 am
by anjanesh
Is there an faster way of reading the last line in a file ?
I want try avoiding going through a list of lines if the data is very huge.

Code: Select all

$csvName = "csv-file.csv";
$fh = @fopen($csvName, "r") or die("Couldnt open file for reading");
while (($data = fgetcsv($fh, 10000, ",")))
 {
        $LastIndex = $data[0];
 }
echo $LastIndex;
@fclose($fh);
I know the solution for indexing is database, but Im looking for something fast enough like unix's tail -1.

Posted: Thu Jun 07, 2007 2:37 pm
by feyd
fseek() to the end, roll back a ways and start reading.

Posted: Thu Jun 07, 2007 10:55 pm
by anjanesh
Thanks.

Code: Select all

<?php
$csvName = "csv-file.csv";
$fh = @fopen($csvName, "r") or die("Couldnt open file for reading");

$pos = 0; 
fseek($fh, $pos--, SEEK_END);
for ($i=0; $i<2; $i++)
 {
        $c = "";
        while (($c = fgetc($fh)) != "\n")
         {
                fseek($fh, $pos--, SEEK_END);
         }
 }

while (($data = fgetcsv($fh, 10000, ",")))
 {
        $LastIndex = $data[0];
 }

echo $LastIndex;
@fclose($fh);
?>