How to Use the File Function in PHP
- 1). Learn the syntax. The complete syntax of file is: array file (string $filename [, int $flags [, resource $context]]).
- 2). Use the $filename parameter to specify the file path. It can be a URL if you have enabled the fopen wrappers. The protocol/wrappers that the file function supports include FTP, FTPS, HTTP and HTTPS. You can also use the file function to establish PHP input/output streams, compression streams and audio streams.
- 3). Specify the behavior of the file function with the optional $flag parameter. The FILE_BINARY constant will cause the file function to read the file content as binary data. FILE_IGNORE_NEW_LINES will prevent the file function from adding a newline character. FILE_SKIP_EMPTY_LINES will skip empty lines. FILE_TEXT will return the file content in UTF-8 encoding. FILE_USE_INCLUDE_PATH will cause the file function to look in the include path for the file.
- 4). Refer to context resource with the $context parameter. You may create this resource with the stream_context_create function.
- 5). Look at the following examples of the file function:
$lines = file('http://www.test.com/');
// read the web page test.com into an array.;
$html = implode('', file('http://www.test.com/'));
// read the web page test.com into a string;
$trimmed = file('temp.txt', FILE_IGNORE_NEW_LINES | ;
FILE_SKIP_EMPTY_LINES);
// read the file temp.txt into an array but do not add any newline characters;
// and skip empty lines.;