Difference between file, file_get_contents, and fo

2019-01-11 18:22发布

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?

标签: php file fopen
2条回答
甜甜的少女心
2楼-- · 2019-01-11 18:55

file — Reads entire file into an array
file_get_contents — Reads entire file into a string
fopen — Opens file or URL

查看更多
何必那么认真
3楼-- · 2019-01-11 18:57

The first two, file and file_get_contents are very similar. They both read an entire file, but file reads the file into an array, while file_get_contents reads it into a string. The array returned by file 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 C fopen function, and simply calling fopen won't do anything but open a stream.

Once you've open a handle to the file, you can use other functions like fread and fwrite to manipulate the data the handle refers to, and once you're done, you will need to close the stream by using fclose. 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.
查看更多
登录 后发表回答