How to read a particular line from a text file in PHP
In this tutorial, I am gonna show you how to read a particular line from a text file in PHP. In the previous posts, I have shown you working with a text file in PHP several times, like
Fetching Text Data From a Text File Using PHP
Get random text by line number from a text file in PHP
How To Read A Text File Line By Line In PHP?
But this time it is going to be quite interesting as I will show you how to read a specific line from a text file using PHP.
Read a particular line from a text file in PHP
I can put the code snippet only. But as it is CodeSpeedy and we always try to give you the easiest understandable code snippet so I will explain everything step by step with an easy example.
We are here to read a specific line from a text file right?
So let’s create a text file first.
Hello I am from line no 1 Hi I am from line no 2 hello again I am from line no 3 Hey I am from line no 4
Okay, that’s enough for this example text file.
Just save the above lines as a text file. You can put any file name. But in this example, I am saving it as mytextfile.txt
Now just make a PHP file to read the text of a particular line
<?php $my_text_file = "mytextfile.txt"; $all_lines = file($my_text_file); echo $all_lines[2]; ?>
Output:
hello again I am from line no 3
Free Currency Converter PHP using Fixer io API
Explanation:
Here we have used one PHP inbuilt function that is file().
The file() function actually returns an array. So here $all_lines variable holds the whole text file as an array.
In order to get a particular line, we need to use the array index. Array indexing starts with zero. So if we wish to get the text of line no 3 then we need to use $all_lines[2]
I hope this tutorial is helpful to you.
Move a file from one directory to another in PHP
Real Time Chat Application PHP With File Transfer System AJAX
Leave a Reply