问题
I want to get the last 15 lines from a large file (30MB) from a SFTP server using PHP.
I tried using the phpseclib's SFTP functionality like that:
include('./Net/SFTP.php');
$sftp = new Net_SFTP("server", 2022);
if (!$sftp->login('username', 'password')) {
exit("Login error");
}
$size = $sftp->size('./file.txt');
$Container = nl2br($sftp->get('./file.txt', false, $size - 5000));
if( !empty($Container) ) {
echo $Container;
} else {
exit("empty file");
}
But this still loads in like 2 minutes for my large file.
Is it possible to get only the last X lines from a large file?
回答1:
The following should result in a blob of text with at least 15 lines from the end of the file that you can then process further with your existing logic. You may want to tweak some of the logic depending on if your file ends with a trailing newline, etc.
$filename = './file.txt'
$filesize = $sftp->size($filename);
$buffersize = 4096;
$offset = $filesize; // start at the end
$result = '';
$lines = 0;
while( $offset > 0 && $lines < 15 ) {
// work backwards
if( $offset < $buffersize ) {
$offset = 0;
} else {
$offset -= $buffer_size;
}
$buffer = $sftp->get($filename, false, $offset, $buffer_size));
// count the number of newlines as we go
$lines += substr_count($buffer, "\n");
$result = $buffer . $result;
}
来源:https://stackoverflow.com/questions/54335695/get-last-15-lines-from-a-large-file-in-sftp-with-phpseclib