Home > Article > Backend Development > php file function_PHP tutorial
php file function
file
(PHP 4, PHP 5)
file - Read the entire file into an array
Description
a list of files (string $file[abstract$flag=0[, resource$background]])
Read the entire file into an array.
Note: You can use file_get_contents() to return file contents as a string.
Parameters
file name
file path.
Tips
URLs can be used as filenames with this feature if open packaging is enabled. See the fopen() function for more details on how to specify a file name and a list of supported protocols/encapsulation protocols for a list of supported URL protocols.
Flag
The optional argument can be a flag, or above, the following constant:
FILE_USE_INCLUDE_PATH
Search include_path in this file.
FILE_IGNORE_NEW_LINES
Don't add a new line at the end of each array element
FILE_SKIP_EMPTY_LINES
Skip empty lines
FILE_TEXT
The returned content is in UTF-8 encoding. You can specify a different encoding to create a custom range. This flag cannot be used with FILE_BINARY. This flag only works since PHP 6.
FILE_BINARY
The content is changed to binary data. This is the default setting and cannot be used with FILE_TEXT. This flag only works since PHP 6.
Background
The stream_context_create() function for background resource creation.
Note: In this case, PHP 5.0.0 is supported. To illustrate, see stream functions.
Return value
Returns the array in file. Each element of the array corresponds to a line in the file, still with newlines attached. On failure, file() returns FALSE.
Note: Each line in the resulting array will include the end of the line, unless FILE_IGNORE_NEW_LINES is used, so you still need to use rtrim() if you don't want to end the line.
NOTE: If PHP does not correctly recognize line endings when either reading a file or creating a Macintosh, enabling the auto_detect_line_endings runtime configuration option may help resolve this issue.
Modify
Release Notes
6.0.0 adds support for the FILE_TEXT and FILE_BINARY flags.
5.0.0 background parameters increased
5.0.0 to pre-PHP 5.0.0 flag parameters are only overridden in include_path and enabled with 1
4.3.0file() becomes binary safe
Example
For example, the example of file No. 1 ( )
// Get a file into an array. In this example we'll go through HTTP to get
// the HTML source of a URL.
$lines = file('http://www.example.com/');
// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
echo "Line #{$line_num} : " . htmlspecialchars($line) . "
n";
}
// Another example, let's get a web page into a string. See also file_get_contents().
$html = implode('', file('http://www.example.com/'));
// Using the optional flags parameter since PHP 5
$trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>