Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a plain text file with php

Tags:

file

text

php

People also ask

How we can read a text file in PHP?

PHP Read File - fread() The fread() function reads from an open file. The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read.

Which code reads the entire content of a file in PHP?

The readfile() function reads the entire content of a file and writes it to the output buffer.

How do I read a text file in HTML?

Make sure you check the source of the document once it's loaded in the browser (all browsers let you do this, right-click "view page source" or similar). If you see the contents of version. txt anywhere in there, you're on the right track, you just need to move it into the body tag so that it will be rendered.

How do I echo content in PHP?

readfile("/path/to/file"); This will read the file and send it to the browser in one command. This is essentially the same as: echo file_get_contents("/path/to/file");


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


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.


You can also produce array by using file:

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

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


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.