PHP Tutorial - PHP file() Function


The file() reads a file into an array.

Each array element contains a line from the file with newline attached.




ParameterIs RequiredDescription
pathRequired.File to read
include_pathOptional.Set to '1' to search for the file in the include_path (in php.ini) as well
contextOptional.Context of the file handle. Skip using NULL.
Context a set of options can modify the behavior of a stream.


Returns the file in an array.

Each element of the array corresponds to a line in the file with the newline attached. If failure, file() returns FALSE.

Example 1

Convert file to an array with each line an element inside that array, use the file() function:

<?PHP//from   w w w .j a  v  a  2 s.c om
      $filename = "c:/abc/test.txt";
      $filearray = file($filename);
      if ($filearray) {
             while (list($var, $val) = each($filearray)) {
                     $val = trim($val);
                     print "Line $var: $val<br />";
      } else {
             print "Could not open $filename.\n";

Example 2

Output a file as an array


The code above generates the following result.

Example 3

The following code shows how to use the optional flags parameter since PHP 5 for file function.

$trimmed = file('test.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
echo $trimmed;

The code above generates the following result.