
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
Read last line from file in PHP
To read last line from file in PHP, the code is as follows −
$line = ''; $f = fopen('data.txt', 'r'); $cursor = -1; fseek($f, $cursor, SEEK_END); $char = fgetc($f); //Trim trailing newline characters in the file while ($char === "
" || $char === "\r") { fseek($f, $cursor--, SEEK_END); $char = fgetc($f); } //Read until the next line of the file begins or the first newline char while ($char !== false && $char !== "
" && $char !== "\r") { //Prepend the new character $line = $char . $line; fseek($f, $cursor--, SEEK_END); $char = fgetc($f); } echo $line;
Output will be the last line of the text file will be read and displayed.
The text file is opened in read mode, and the cursor is set to point to -1, i.e. nothing initially. The ‘fseek’ function is used to move to the end of the file or the last line. The line is read until a newline is encountered. After this, the read characters are displayed.
- Related Articles
- How to read only 5 last line of the text file in PHP?
- Read Random Line From a File in Linux
- Read file line by line using C++
- How to read a Specific Line From a File in Linux?
- How to read a file from command line using Python?
- How to read an entire line from a text file using Python?
- How to read complete text file line by line using Python?
- Java Program to Read a Large Text File Line By Line
- Write a Python program to read an Excel data from file and read all rows of first and last columns
- Golang program to read the content of a file line by line
- How to read data from .csv file in Java?
- Read/Write Class Objects from/to File in C++
- Read Data from a Text File using C++
- How to read the data from a file in Java?
- How to read a text file from resources in Kotlin?

Advertisements