Read a plain text file with php

PhpFileText

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

<?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.

Solution 2 - Php

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.

Solution 3 - Php

You can also produce array by using file:

$array = file('/path/to/text.txt');

Solution 4 - Php

$filename = "fille.txt";
$fp = fopen($filename, "r");

$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 with each newline character in the file.

Solution 5 - Php

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.

Solution 6 - Php

Try something like this:

$filename = 'file.txt';

$data = file($filename);
foreach ($data as $line_num=>$line)
{
    echo 'Line # <b>'.$line_num.'</b>:'.$line.'<br/>';
}

Solution 7 - Php

$file="./doc.txt";
$doc=file_get_contents($file);

$line=explode("\n",$doc);
foreach($line as $newline){
    echo '<h3 style="color:#453288">'.$newline.'</h3><br>';
    
}

Solution 8 - Php

> 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);
?>

Solution 9 - Php

$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);

Solution 10 - Php

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

Solution 11 - Php

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...

Solution 12 - Php

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: ", $version);

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDomingoSLView Question on Stackoverflow
Solution 1 - PhpPayloadView Answer on Stackoverflow
Solution 2 - PhpzzzzBovView Answer on Stackoverflow
Solution 3 - PhpsubositoView Answer on Stackoverflow
Solution 4 - PhpUllas PrabhakarView Answer on Stackoverflow
Solution 5 - PhpDaiYoukaiView Answer on Stackoverflow
Solution 6 - PhpSvinjicaView Answer on Stackoverflow
Solution 7 - PhpSani KamalView Answer on Stackoverflow
Solution 8 - Phpuser8439630View Answer on Stackoverflow
Solution 9 - PhpDimuthu LakshanView Answer on Stackoverflow
Solution 10 - Phpuser14779464View Answer on Stackoverflow
Solution 11 - PhpdynastonedView Answer on Stackoverflow
Solution 12 - PhpWiiLFView Answer on Stackoverflow