How to read only 5 last line of the text file in PHP?

前端 未结 18 1648
陌清茗
陌清茗 2020-11-28 08:45

I have a file named file.txt which is update by adding lines to it.

I am reading it by this code:

$fp = fopen(\"file.txt\", \"r\");
$da         


        
18条回答
  •  一向
    一向 (楼主)
    2020-11-28 09:25

    Here is my solution:

    /**
     *
     * Reads N lines from a file
     *
     * @param type $file       path
     * @param type $maxLines   Count of lines to read
     * @param type $reverse    set to true if result should be reversed.
     * @return string
     */
    public function readLinesFromFile($file, $maxLines, $reverse=false)
    {
        $lines = file($file);
    
        if ($reverse) {
            $lines = array_reverse($lines);
        }
    
        $tmpArr = array();
    
        if ($maxLines > count($lines))
            exit("\$maxLines ist größer als die Anzahl der Zeilen in der Datei.");
    
        for ($i=0; $i < $maxLines; $i++) {
            array_push($tmpArr, $lines[$i]);
        }
    
        if ($reverse) {
            $tmpArr = array_reverse($tmpArr);
        }
    
        $out = "";
        for ($i=0; $i < $maxLines; $i++) {
            $out .= $tmpArr[$i] . "
    "; } return $out; }

提交回复
热议问题