68

I have a text file with this information in my server:

Data1
Data2
Data3
.
.
.
DataN

How do I read all the information from the text file (line by line) using PHP?

ZygD
24.8k41 gold badges107 silver badges145 bronze badges
asked Nov 5, 2010 at 3:03

12 Answers 12

119
<?php
$fh = fopen('filename.txt','r');
while ($line = fgets($fh)) {
 // <... Do your work with the line ...>
 // echo($line);
}
fclose($fh);
?>

This will give you a line by line read.. read the notes at php.net/fgets regarding the end of line issues with Macs.

answered Nov 5, 2010 at 3:13
Sign up to request clarification or add additional context in comments.

Comments

28

http://php.net/manual/en/function.file-get-contents.php
http://php.net/manual/en/function.explode.php

$array = explode("\n", file_get_contents($filename));

This wont actually read it line by line, but it will get you an array which can be used line by line. There are a number of alternatives.

answered Nov 5, 2010 at 3:09

1 Comment

I assume this will "explode" your memory with a very large dataset
16
$filename = "file.txt";
$lines = array();
$fp = fopen($filename, "r");
if(filesize($filename) > 0){
 $content = fread($fp, filesize($filename));
 $lines = explode("\n", $content);
 fclose($fp);
}
print_r($lines);

In this code full content of the file is copied to the variable $content and then split it into an array variable $lines with each newline character in the file.

Kamlesh
6,2571 gold badge51 silver badges55 bronze badges
answered Mar 6, 2012 at 9:24

Comments

15

You can also produce array by using file:

$array = file('/path/to/text.txt');
answered Nov 5, 2010 at 3:53

1 Comment

This is handy, but note: each line has new line character at end :D
5

W3Schools is your friend: http://www.w3schools.com/php/func_filesystem_fgets.asp

And here: http://php.net/manual/en/function.fopen.php has more info on fopen including what the modes are.

What W3Schools says:

<?php
$file = fopen("test.txt","r");
while(! feof($file))
 {
 echo fgets($file). "<br />";
 }
fclose($file);
?> 

fopen opens the file (in this case test.txt with mode 'r' which means read-only and places the pointer at the beginning of the file)

The while loop tests to check if it's at the end of file (feof) and while it isn't it calls fgets which gets the current line where the pointer is.

Continues doing this until it is the end of file, and then closes the file.

answered Nov 5, 2010 at 3:08

Comments

3

Try something like this:

$filename = 'file.txt';
$data = file($filename);
foreach ($data as $line_num=>$line)
{
 echo 'Line # <b>'.$line_num.'</b>:'.$line.'<br/>';
}
BrokenBinary
7,9493 gold badges46 silver badges55 bronze badges
answered Dec 4, 2015 at 13:52

Comments

2
$file="./doc.txt";
$doc=file_get_contents($file);
$line=explode("\n",$doc);
foreach($line as $newline){
 echo '<h3 style="color:#453288">'.$newline.'</h3><br>';
}
Vivz
6,6282 gold badges19 silver badges34 bronze badges
answered Dec 23, 2017 at 6:19

Comments

2

Unless specifically defining where and how to handle the string, simply use file_get_contents(). No need for long blocks of iteration and workarounds.

For example, reading version from latestversion.txt in /client/ with a fallback using a ternary operator (condition ? do : else)

$version = file_exists("client/latestversion.txt") ? file_get_contents("client/latestversion.txt") : "0.0.0.0";

Here, we are confirming latestversion.txt does exist, and requesting to read it, otherwise output "0.0.0.0". Its a one-liner that gets the job done.

Then you simply echo out

echo "The version is: " . $version;

Or you can call it like this

printf("The version is: %s", $version);

Cleansing the string at this point would be advised depending on the access permissions to that file if that is the case.

answered Dec 17, 2021 at 21:23

Comments

0

You can read a group of txt files in a folder and echo the contents like this.

 <?php
$directory = "folder/";
$dir = opendir($directory);
$filenames = [];
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if($type !== 'file') continue;
$filenames[] = $filename;
}
closedir($dir);
?>
answered Sep 25, 2019 at 1:21

Comments

0
$aa = fopen('a.txt','r');
echo fread($aa,filesize('a.txt'));
$a = fopen('a.txt','r');
while(!feof($a)){echo fgets($a)."<br>";}
fclose($a);
David Buck
3,88640 gold badges54 silver badges74 bronze badges
answered Apr 29, 2020 at 7:40

2 Comments

While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
...David's comment is especially important if a question already contains a lot of answers. Adding a new one is fine, as long as it contains some new insights
0

$your_variable = file_get_contents("file_to_read.txt");

answered Dec 7, 2020 at 11:04

1 Comment

Please don't post only code as an answer, but also provide an explanation of what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes
0

The code posted above from Payload works great. I'd like to add something to this because others might run into the same problem. I used your code and was trying to compare a value with a $line that was fetched from the .txt file. Even though I know my keyword matches a line I kept getting an error. this is an example of the code...

textfile.txt content example:
text1
text2
keyword
text3

$keyword = 'keyword';
while($line = fgets($txt_file)) {
 if (substr_compare($line, $keyword, 0) === 0) { 
 $value = $line;
 }
}
echo $value; // returns nothing because the if statement was false

The problem is each $line is carrying a new line at the end of it. But in my case I just used enter for a new line when creating the .txt file, it's not specified with something like "\n" or idk "\r\n". Anyways, if you're running into the same problem be sure to trim() the $line before you work with it to get rid of any whitespace or in this case the new line or you might keep running into errors. the shortest and easiest way to do this without getting weird results is to simply trim it right in the while statement like this...

while($line = trim(fgets($txt_file))) {
 
 if (substr_compare($line, $keyword, 0) === 0) { 
 $value = $line;
 }
} 
echo $value; // result: keyword

and yes i did get some weird results trying to throw the trim() around $line inside the substr_compare() function, even though the if statement result was TRUE the $value would have a result of " keyword " with a space on the beginning and end of the keyword. weird stuff...

answered Jul 9, 2021 at 9:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.