How To Read A Text File Line By Line In PHP?
Hello, guys! I am here again with another simple and easy PHP tutorial. In this tutorial, I will show you how to read a text file line by line. Like any other tutorial, I will also show you the simple example code so that you will understand it in a better way.
Example code to read text file line by line in PHP
Suppose there is a text file which contains a domain name in each line. For example, suppose the name the text file is domainlist.txt which contains one domain name per line like below:
codespeedy.com eyeswift.com google.com facebook.com twitter.com linkedin.com
Now below is the PHP code which will read the text file and echo each domain name from each line by using a while loop:
<?php if ($file = fopen("domainlist.txt", "r")) { while(!feof($file)) { $textperline = fgets($file); echo $textperline; } fclose($file); } ?>
The above code will show all the domain in one line.
Arrange the domains per line and make it clickable link
Now I am going to show you how to make the domains clickable and arrange it per line. The PHP code I will give you is the modification of previous code. below is the code:
<?php if ($file = fopen("domainlist.txt", "r")) { while(!feof($file)) { $textperline = fgets($file); echo " <a href='http://" .$textperline. "'>" . $textperline . "</a><br/><br/> "; } fclose($file); } ?>
The above few line PHP code will arrange the domains per line with anchor text. Test the code on your server and you will see each domain per line is a clickable link.
Another think I want to share with you. If you remove the .txt extension from the text file and use the code without any extension then it will also work as same as it is working now. In that case, you also have to remove the extension from PHP code and the code for locating file path will be:
$file = fopen("domainlist", "r") //the .txt has removed
At the end, I want to inform you that this tutorial can help a developer in many ways. In many cases, you may need to take data from users. You can direct the users to send the data as a text file and inform the user that the required data should be per line basis.
Leave a Reply