復制代碼 代碼如下:
$fp->seek($startLine - 1);
復制代碼 代碼如下:
function getFileLines($filename, $startLine = 1, $endLine = 50, $method = 'rb'){
$content = array();
if (version_compare(PHP_VERSION, '5.1.0', '>=')) { // 判斷php版本(因為要用到SplFileObject,PHP>=5.1.0)
$count = $endLine - $startLine;
$fp = new SplFileObject($filename, $method);
$fp->seek($startLine - 1); // 轉到第N行, seek方法參數從0開始計數
for ($i = 0; $i <= $count; ++$i) {
$content[] = $fp->current(); // current()獲取當前行內容
$fp->next(); // 下一行
}
} else { //PHP<5.1
$fp = fopen($filename, $method);
if (!$fp)
return 'error:can not read file';
for ($i = 1; $i < $startLine; ++$i) { // 跳過前$startLine行
fgets($fp);
}
for ($i; $i <= $endLine; ++$i) {
$content[] = fgets($fp); // 讀取文件行內容
}
fclose($fp);
}
return array_filter($content); // array_filter過濾:false,null,''
}
新聞熱點
疑難解答