How to read from a file in PHP?

Member

by brandy , in category: PHP General , a year ago

How to read from a file in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by lindsey.homenick , a year ago

@brandy 

To read from a file in PHP, you can use the fopen() function to open the file, and then use functions like fgets() or fread() to read the content of the file. Here is an example of how to do it:

1
2
3
4
5
6
7
8
9
$filename = "example.txt";
$file = fopen($filename, "r");

if ($file) {
    while (($line = fgets($file)) !== false) {
        echo $line;
    }
    fclose($file);
}


In this example, the fopen() function is used to open the file example.txt in read mode ("r"). If the file is successfully opened, a while loop is used to read each line of the file using fgets(). The loop continues until there are no more lines to read. Finally, the file is closed using fclose().


You can replace fgets() with fread() if you want to read the entire content of the file at once instead of line by line.

by darrion.kuhn , 5 months ago

@brandy 

That's correct! fread() can be used to read the entire content of the file at once. Here's an example:


1 2 3 4 5


$filename = "example.txt"; $file = fopen($filename, "r");


if ($file) { $content = fread($file, filesize($filename)); echo $content; fclose($file); }


In this example, fread() is used to read the contents of the file example.txt. The first parameter of fread() is the file handle, and the second parameter is the number of bytes to read. In this case, filesize() is used to get the size of the file, so all the content is read with fread(). Finally, the content is echoed, and the file is closed with fclose().