Handling files is important in every programming language, and in PHP we have all the standard features. We can open a file and read in its lines.
With a finally block, we can ensure a file is always closed after using it. This can improve reliability and prevent files from being left open.
This program opens an "example.txt" file in the local directory. We can place the file in the current directory where the terminal is open.
string
lines from the file.fgets()
and call trim()
to eliminate ending newlines.// Step 1: create an empty array. $lines = []; // Step 2: open a file for reading. $f = fopen("example.txt", "r"); // Step 3: read each line with fgets, and trim each line. try { while ($line = fgets($f)) { $lines[] = trim($line); } } finally { // Step 4: close the file. fclose($f); } // Step 5: print the lines array. var_dump($lines);array(3) { [0]=> string(13) "Hello friends" [1]=> string(10) "This is an" [2]=> string(7) "example" }
Files in PHP can be opened, read in, and then closed. We can handle lines individually, which tends to lead to the clearest code when we want to parse in settings files.