PHP file() Function

Definition

The file() reads a file into an array.

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

Syntax

file(path,include_path,context)

Parameter

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.

Return

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 av  a  2s . co  m*/
      $filename = "c:/abc/test.txt";
      $filearray = file($filename);
      if ($filearray) {
             while (list($var, $val) = each($filearray)) {
                     ++$var;
                     $val = trim($val);
                     print "Line $var: $val<br />";
             }
      } else {
             print "Could not open $filename.\n";
      }
?>

Example 2

Output a file as an array


<?php
print_r(file("test.txt"));
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions