php fseek讀取檔案(從後往前讀取)
阿新 • • 發佈:2019-01-03
public static function readBySeek($filepath,$lines,$revers = false){ $offset = -1; $c = ''; $read = ''; $i = 0; $fp = fopen($filepath, "r"); while( $lines && fseek($fp, $offset, SEEK_END) >= 0 ) { $c = fgetc($fp); if($c == "\n" || $c == "\r"){ $lines--; if( $revers ){ $read[$i] = strrev($read[$i]); $i++; } } if( $revers ) $read[$i] .= $c; else $read .= $c; $offset--; } fclose($fp); if( $revers ){ if($read[$i] == "\n" || $read[$i] == "\r") array_pop($read); else $read[$i] = strrev($read[$i]); //反轉字串 return implode('',$read); } return strrev(rtrim($read,"\n\r")); }