Jump to content

Read from the LAST line of a CSV file (without knowing line number)


schapel

Recommended Posts

Is there a way to read from the very last line of a CSV file that has been opened via PHP fopen() ?  The trick is that this is a file that has been uploaded by a user, and opened by the server, but could have 100 lines or it could have 100,000.  We just need to read from the very last line specifically of the file, which is basically a line containing an array of variables imprinted on the file during upload.

 

Any thoughts on how to accomplish this?

 

Thanks!

Got it, but let me throw out a solution and see if it's possible? What if the script already had a total line count from the CSV file (which it determines during a normal import). Is it possible to use some function to utilize this 'total linecount' number to read from that specific line only (which would be the last line of the file).

I suppose you could do something like this. It will search backwards for a newline. It isn't tested.

 

<?php
$bufferSize = 10;
$file = 'file.txt';

$size = filesize($file);

$fp = fopen($file, 'a');

$buffer = '';
for ($pos = $size - $bufferSize;; $pos -= $bufferSize) {
    $pos = max(0, $pos);
    fseek($fp, $pos2);
    
    $b = fread($fp, $bufferSize);
    $nlPos = strrpos($b, "\n");
    
    if ($nlPos !== false) {
        $buffer = substr($b, $nlPos) . $buffer;
        break;
    }
    else {
        $buffer = $b . $buffer;
    }
    
    if ($pos == 0) {
        break;
    }
}

$lastLine = trim($buffer);

 

Is it possible to use some function to utilize this 'total linecount' number to read from that specific line only (which would be the last line of the file).

 

You don't know how many lines there are before you've read the entire string.

Okay, I just tested. This will work:

<?php
$bufferSize = 10;
$file = 'test.txt';

$size = filesize($file);

$fp = fopen($file, 'r');
$buffer = '';
for ($pos = $size - $bufferSize;; $pos -= $bufferSize) {
    $pos = max(0, $pos);
    fseek($fp, $pos);
    
    $b = rtrim(fread($fp, $bufferSize));
    $nlPos = strrpos($b, "\n");
    
    if ($nlPos !== false) {
        $buffer = substr($b, $nlPos) . $buffer;
        break;
    }
    else {
        $buffer = $b . $buffer;
    }
    
    if ($pos == 0) {
        break;
    }
}

$lastLine = trim($buffer);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.