PHP file() Function
The PHP file() function reads a file into an array. Each element of the array corresponds to a line in the file, with the newline character still attached.
Note: The file_get_contents() function is used to return the contents of a file as a string.
Syntax
file(filename, flags, context)
Parameters
filename |
Required. Specify the path to the file to read. A URL can be used as a filename with this function if the fopen wrappers have been enabled. |
flags |
Optional. Specify how to open/read the file. The possible values are:
|
context |
Optional. Specify the context of the file handle. Context is a set of options that can modify the behavior of a stream. |
Return Value
Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, it returns false.
Note: Each line in the resulting array will include the newline character, unless FILE_IGNORE_NEW_LINES is used.
Exceptions
Generates an E_WARNING level error if filename is not found.
Example: reading a file into an array
Lets assume that we have a file called test.txt. This file contains following content:
This is a test file. It contains dummy content.
In the example below, file() function is used to read the content of it into an array.
<?php $filename = "test.txt"; //reading the content of $filename $lines = file($filename); //displaying the array print_r($lines); ?>
The output of the above code will be:
Array ( [0] => This is a test file. [1] => It contains dummy content. )
Example: remove newline character
By using FILE_IGNORE_NEW_LINES flag, we can remove newline character at the end of each array element. Consider the example below:
<?php $filename = "test.txt"; //reading the content of $filename $lines = file($filename, FILE_IGNORE_NEW_LINES); //displaying the array print_r($lines); ?>
The output of the above code will be:
Array ( [0] => This is a test file. [1] => It contains dummy content. )
❮ PHP Filesystem Reference