PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Moderator: General Moderators
anjanesh
DevNet Resident
Posts: 1679 Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India
Post
by anjanesh » Thu Jun 07, 2007 10:33 am
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 .
feyd
Neighborhood Spidermoddy
Posts: 31559 Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA
Post
by feyd » Thu Jun 07, 2007 2:37 pm
fseek() to the end, roll back a ways and start reading.
anjanesh
DevNet Resident
Posts: 1679 Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India
Post
by anjanesh » Thu Jun 07, 2007 10:55 pm
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);
?>