The file() function reads a file into an array.
file(file_path,flag,context)
file − Path of the file.
flag − The optional parameter flags can be one, or more, of the following constants −
FILE_USE_INCLUDE_PATH − Search for the file in the include_path.
FILE_IGNORE_NEW_LINES − Do not add newline at the end of each array element.
FILE_SKIP_EMPTY_LINES − Skip empty lines.
FILE_TEXT − The content is returned in UTF-8 encoding. You can specify a different encoding by creating a custom context. This flag cannot be used with FILE_BINARY. This flag is only available since PHP 6.
FILE_BINARY − The content is read as binary data. This is the default setting and cannot be used with FILE_TEXT. This flag is only available since PHP 6.
context − It modifies the behaviour of the stream.
The file() function returns the file in an array, whereas it returns false on failure.
Let’s say we have a file “continents.txt” with the following content and lines.
The Earth has seven continents. The continents are: Asia, Africa, North America, South America, Antarctica, Europe, and Australia. Asia is the largest in area. Australia is the smallest in terms of area.
<?php print_r(file("continents.txt")); ?>
Array ( [0] => The Earth has seven continents. [1] => The continents are: Asia, Africa, North America, South America, Antarctica, Europe, and Australia. [2] => Asia is the largest in area. [3] => Australia is the smallest in terms of area. )