PHP,如何从文件中只读取几行

PHP,如何从文件中只读取几行,php,fopen,fclose,Php,Fopen,Fclose,这是插入文件,它一次放入一行。 例如,我只想读最后10行 $file = SITE_ROOT."logs/log.txt"; if ($handle = fopen($file, 'a+b')) { $content = Session::get('username') . " has logged out on - " . datetime_to_text("now") . "\r\n"; fwrite($handle, $co

这是插入文件,它一次放入一行。 例如,我只想读最后10行

$file = SITE_ROOT."logs/log.txt";

        if ($handle = fopen($file, 'a+b')) {
            $content = Session::get('username') . " has logged out on - " . datetime_to_text("now") . "\r\n";
            fwrite($handle, $content);
            fclose($handle);
        } else {
            echo 'Culd not open file for writing.';
        }
这就是我读它们的方式,全部都读

$file = SITE_ROOT . "logs/log.txt";
                                $content = "";
                                if ($handle = fopen($file, 'r')) {
                                    while (!feof($handle)) {
                                        $content .= '<li><a href="#">' . fgets($handle) . '</a></li>';
                                        echo count($handle);
                                    }
                                    fclose($handle);
                                }

                                echo nl2br($content);
$file=SITE\u ROOT。“logs/log.txt”;
$content=“”;
如果($handle=fopen($file,'r')){
而(!feof($handle)){
$content.='
  • '; 回波计数($handle); } fclose($handle); } echo nl2br($content);
    如何只读10

    完成后,我找到了我想要的答案

    Thx, i found useffull this one.
    
    
    
    $file = SITE_ROOT . "logs/log.txt";
    $data = array_slice(file($file), -10);
    $data1 = file($file);
    foreach ($data as $line) {
    echo '<li><a href="#">'. nl2br($line) . '</a></li>';
    }
    
    Thx,我找到了这个。 $file=SITE\u ROOT。“logs/log.txt”; $data=数组×片(文件($file),-10); $data1=文件($file); foreach($行数据){ 回音“
  • ”; } 这一行实际上是在“读”这一行,所以把它改成这个

    $i=0;
    $max=10;
    while (!feof($handle) && ($i++ < $max)) {
    
    $i=0;
    $max=10;
    而(!feof($handle)&($i++<$max)){
    
    这将设置计数器并计数,直到达到$max。 抱歉,我错过了最后10行。只看到代码块之间的10行


    为最后的x行提供了很好的信息

    是的,我已经找到了这一行,但我想阅读las 10条目。
    $i=0;
    $max=10;
    while (!feof($handle) && ($i++ < $max)) {