Home
Map
File Handling (fopen and fgets)Handle files with the fopen and fgets functions. Read in lines from a file and place them in an array.
PHP
This page was last reviewed on May 19, 2023.
File. 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.
An example. 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.
Step 1 We create an empty array with the short syntax form. This is where we will place the string lines from the file.
array
Step 2 We open the "example.txt" file for reading. The arguments are the file path, and "r" for reading.
Step 3 We read each line into the array with fgets() and call trim() to eliminate ending newlines.
Step 4 We close the file inside a finally block, which will eliminate PHP keeping files open when not needed.
Step 5 We print the lines in the file. We can see there are no trailing newlines, and 3 strings total.
// 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 19, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.