252 of 410 menu

The file Function

The file function reads the contents of a file and returns it as an array, where each element corresponds to a line in the file. The first parameter of the function is the path to the file, and the second (optional) one is flags to modify the function's behavior.

Syntax

file(string $filename, int $flags = 0);

Flags

Flag Description
FILE_USE_INCLUDE_PATH Search for the file in the directories specified in the include_path.
FILE_IGNORE_NEW_LINES Do not add newline characters (\n) to the end of each array element.
FILE_SKIP_EMPTY_LINES Skip empty lines when forming the array.

Example

Let's read the contents of the file 'test.txt' and output the array of lines:

<?php $res = file('test.txt'); print_r($res); ?>

Example

Using the FILE_IGNORE_NEW_LINES flag to remove newline characters:

<?php $res = file('test.txt', FILE_IGNORE_NEW_LINES); print_r($res); ?>

Example

Reading a file with simultaneous use of multiple flags:

<?php $res = file('test.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); print_r($res); ?>

See Also

  • the file_get_contents function,
    which reads the contents of a file into a string
  • the fopen function,
    which opens a file or URL
  • the readfile function,
    which outputs the contents of a file
  • the parse_ini_file function,
    which processes a configuration file
byenru