PHP: How Do I Read From a Text File?

How do I read from text file using PHP under Linux or UNIX?

PHP does supports the file reading and writing. You can open a file using the fopen() function. Once the file is open, you can use the fgets() function to read from the file.

For example, if you wish to open file called /tmp/file1.txt then following PHP code will help you to read file. fopen() will open fine in r (read) mode. Then while loop will open file using fgets() function till end of file:

php source code

<html>
<head>
<title>File read demo</title>
</head>
<body>
<?php
$file = "/tmp/file1.txt";
$f = fopen($file, "r");
while ( $line = fgets($f, 1000) ) {
print $line;
}
?>
</body>
</html>

See fopen() and fgets() for more information.

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.