how do you read the last line in php and parse out certain columns

后端 未结 3 467
小蘑菇
小蘑菇 2021-01-27 12:02

I am very new to php. I\'d really appreciate all the help here.

I am using sftp to login to a server and get a file. I am only interested in the last line in that file.

3条回答
  •  甜味超标
    2021-01-27 12:59

    Last line

    Might be overkill if the file is small, but wrote this function a while ago. Returns the last n lines of a file/stream.

    function tail($file, $lines = 10, $buffer = 4096)
    {
            if(is_resource($file) && (get_resource_type($file) == 'file' || get_resource_type($file) == 'stream'))
                    $f = $file;
            elseif(is_string($file))
                    $f = fopen($file, 'rb');
            else
                    throw new Exception('$file must be either a resource (file or stream) or a filename.');
    
            $output = ''; 
            $chunk = '';
    
            fseek($f, -1, SEEK_END);
    
            if(fread($f, 1) != "\n")
                    $lines -= 1;
    
            while(ftell($f) > 0 && $lines >= 0)
            {
                    $seek = min(ftell($f), $buffer);
                    fseek($f, -$seek, SEEK_CUR);
    
                    $output = ($chunk = fread($f, $seek)).$output;
                    fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR);
                    $lines -= substr_count($chunk, "\n");
            }
    
            while($lines++ < 0)
                    $output = substr($output, strpos($output, "\n")+1);
    
            fclose($f); 
            return $output; 
    }
    

    Columns

    If tab separated, simply do a split and assign what you want to variables.

    $columns = explode("\t",$line);
    
    $foo = $columns[15];
    ...
    

提交回复
热议问题