I am new to PHP, and I am not quite sure: what is the difference between the file()
, file_get_contents()
, and fopen()
functions, and when should I use one over the other?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
file
— Reads entire file into an arrayfile_get_contents
— Reads entire file into a stringfopen
— Opens file or URLThe first two,
file
andfile_get_contents
are very similar. They both read an entire file, butfile
reads the file into an array, whilefile_get_contents
reads it into a string. The array returned byfile
will be separated by newline, but each element will still have the terminating newline attached, so you will still need to watch out for that.The
fopen
function does something entirely different—it opens a file descriptor, which functions as a stream to read or write the file. It is a much lower-level function, a simple wrapper around the Cfopen
function, and simply callingfopen
won't do anything but open a stream.Once you've open a handle to the file, you can use other functions like
fread
andfwrite
to manipulate the data the handle refers to, and once you're done, you will need to close the stream by usingfclose
. These give you much finer control over the file you are reading, and if you need raw binary data, you may need to use them, but usually you can stick with the higher-level functions.So, to recap:
file
— Reads entire file contents into an array of lines.file_get_contents
— Reads entire file contents into a string.fopen
— Opens a file handle that can be manipulated with other library functions, but does no reading or writing itself.