read a file in php

To read a file in PHP, we can use the fopen() function to open the file and return a file pointer. Then we can use the fgets() function to read the file line by line.

Here's an example:

main.php
$file = fopen("filename.txt", "r") or die("Unable to open file!");

// Output one line until end-of-file
while(!feof($file)) {
  echo fgets($file) . "<br>";
}

fclose($file);
175 chars
9 lines

In this example, we first use the fopen() function to open the "filename.txt" file in "read" mode. We use the "or die()" statement to display an error message and stop the script execution if the file is unable to be opened.

Then we use a while loop and the feof() function to read the file line by line until we reach the end-of-file. Inside the loop, we use the fgets() function to read and output each line of the file.

Finally, we use the fclose() function to close the file.

Note that there are other functions and methods to read files in PHP, such as file_get_contents() and SplFileObject, however, the fopen() and fgets() functions provide a basic and efficient way to read files in PHP.

gistlibby LogSnag