【问题标题】:Get Last row value and N row value before last row获取最后一行之前的最后一行值和 N 行值
【发布时间】:2014-04-25 13:13:16
【问题描述】:

如何使用PHP读取并回显TEXT文件最后一行之前的N行?

file.txt 中的示例

test1
test2
test3
test4
test5
test6
test7

我想获取最后一行的值和最后一行之前的 3 行。 所以结果将是:

test4
test7

这是我目前的代码(只显示最后一行)

$line = '';
$f = fopen('\\\\192.168.183.28\\wk$\\sbin\\file.txt', 'r');
            $cursor = -1;

            fseek($f, $cursor, SEEK_END);
            $char = fgetc($f);

            while ($char === "\n" || $char === "\r") {
                fseek($f, $cursor--, SEEK_END);
                $char = fgetc($f);
            }

            while ($char !== false && $char !== "\n" && $char !== "\r")
            {
                $line = $char . $line;
                fseek($f, $cursor--, SEEK_END);
                $char = fgetc($f);
            }

            $future_sn = substr($line, 28, 36);

有什么建议吗?

【问题讨论】:

  • 你试过什么?显示一些代码。如果您付出一些努力,人们会很乐意提供帮助。
  • 对不起...到目前为止我附上了我的代码(它只显示最后一行的值)

标签: php


【解决方案1】:

试试

$array = explode("\n", file_get_contents('file.txt'));
// counting array and get key for prev
$prev_third = count($array)-4;
echo end($array); // test7
echo $array[$prev_third]; //test4 

【讨论】:

    【解决方案2】:

    您可以使用 fgets() 来读取文件并保留一个计数器来跟踪最后一行。您可以通过 mod(%) 计数器从最后一行获得 3 行。

    $handle = fopen("input.txt", "r");
    $lastRow = "";
    $last3Ahead = "";
    $counter = 0;
    $a = "";
    $b = "";
    $c = "";
    if ($handle) {
        while (($line = fgets($handle)) !== false) {
        if($counter == 0) $a = $line;
        if($counter == 1) $b = $line;
        if($counter == 2) $c = $line;
        $lastRow = $line ;
    
        if($counter >= 3) {
          $last3Ahead  = $a;
          $a = $b;
          $b = $c;
          $c = $line
        } 
        $counter++;
    
    
     } else {
    // error opening the file.
     } 
      fclose($handle);
      echo $lastRow. "<br>" ;     //last row
      echo $last3Ahead  . "<br>"; //3 row before last;
    

    【讨论】:

    • 这个答案不起作用。 last3ahead 的 if 逻辑不会按照您的想法进行。
    • 对不起,我错过了 !(not) 运算符,编辑它现在应该可以工作了
    猜你喜欢
    • 1970-01-01
    • 2017-11-15
    • 2014-09-29
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 2012-02-16
    • 2019-04-02
    • 1970-01-01
    相关资源
    最近更新 更多