Reading line by line in php

Topic

How to Read a file line by line using php?

Explanation

Reading a file line by line
For an example we will use the file test.txt to explain it
The real difference comes in using the method file() instead of fopen()
Step 1:
Define the file name in to a variable
Example: $file1 = "./test.txt";
Step 2:
Create an instance of the file using the method file('filename')
Example: $lines = file($file1);
Here we create a file instance for the file by passing the variable $file1 created in step 1. The result is stored in the variable $lines, which will be an array of lines.
Step 3:
Now we will use a loop to capture every element in the array one by one and print the lies. Example: foreach($lines as $line_num => $line)
{
echo $line;
echo "<br>";
}
In the above code we used the loop foreach to capture the elements or objects in the array of lines ($lines). Each line is printed used the code "echo $line";
Example Code:
<?php
$file1 = "./test.txt";
$lines = file($file1);
foreach($lines as $line_num => $line)
{
echo $line;
echo "<br>";
}
?>

The Result is
Name - HIOX INDIA
Topic - tutorials

PHP Topics