
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 === "\n" || $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 !== "\n" && $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 Questions & Answers
- How to read only 5 last line of the text file in PHP?
- Read file line by line using C++
- 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?
- What's an easy way to read a random line from a file in the Unix command line?
- Write a Python program to read an Excel data from file and read all rows of first and last columns
- Read Data from a Text File using C++
- How to read data from .csv file in Java?
- Read/Write Class Objects from/to File in C++
- How to read a line from the console in C#?
- How to read only the first line of a file with Python?
- How to read data from *.CSV file using JavaScript?
- Read integers from a text file with C++ ifstream
- How to read data from a file using FileInputStream?
Advertisements