This seems like it should be a simple thing to do but I'm having a bit of trouble with fgetc() when returning the last line of a open file handle. what I'm trying to do is return the last line written to the handle, I have the following which works if the handle has only one line:
function getLastLineFromHandle($handle)
{
$seeker = function($handle) use (&$seeker) {
fseek($handle, -1, SEEK_CUR);
return ftell($handle) ?
$seeker($handle) :
$handle;
};
return trim(fgets($seeker($handle)));
}
$handle = fopen('php://temp', 'w+');
fwrite($handle, 'Hello World'.PHP_EOL);
//prints Hello World
print getLastLineFromHandle($handle);
The problem is when I have multiple lines written to the handle, adding an fgetc() to the check condition doesn't seems to work for example:
function getLastLineFromHandle($handle)
{
$seeker = function($handle) use (&$seeker) {
fseek($handle, -1, SEEK_CUR);
return ftell($handle) && fgetc($handle) != PHP_EOL ?
$seeker($handle) :
$handle;
};
return trim(fgets($seeker($handle)));
}
This returns blank if multiple lines are written to the handle and fgetc($handle) seems to return the same character each time?
I'm sure there is something very simple that I've missed, but any pointers would be great as this is driving me crazy!
Thanks.