php PHP中file、file_get_contents和fopen的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24007898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:05:47  来源:igfitidea点击:

Difference between file, file_get_contents, and fopen in PHP

phpfilefopen

提问by c00L

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()file_get_contents()以及fopen()功能,当我应该使用一个比其他?

回答by Alexis King

The first two, fileand file_get_contentsare very similar. They both read an entire file, but filereads the file into an array, while file_get_contentsreads it into a string. The array returned by filewill be separated by newline, but each element will still have the terminating newline attached, so you will still need to watch out for that.

前两个,filefile_get_contents非常相似。它们都读取整个文件,但file将文件读入数组,同时file_get_contents将其读入字符串。返回的数组file将由换行符分隔,但每个元素仍会附加终止换行符,因此您仍然需要注意这一点。

The fopenfunction does something entirely different—it opens a file descriptor, which functions as a stream to read orwrite the file. It is a much lower-level function, a simple wrapper around the C fopenfunction, and simply calling fopenwon't do anything but open a stream.

这个fopen函数做一些完全不同的事情——它打开一个文件描述符,它作为一个流来读取写入文件。它是一个低得多的函数,是 Cfopen函数的一个简单包装器,简单的调用fopen除了打开一个流之外什么也做不了。

Once you've open a handle to the file, you can use other functions like freadand fwriteto 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.

打开文件句柄后,您可以使用其他函数(如fread和 )fwrite来操作句柄引用的数据,完成后,您需要使用fclose. 这些使您可以更好地控制正在读取的文件,如果您需要原始二进制数据,您可能需要使用它们,但通常您可以坚持使用更高级别的函数。

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.
  • file— 将整个文件内容读入行数组。
  • file_get_contents— 将整个文件内容读入一个字符串。
  • fopen— 打开可以用其他库函数操作的文件句柄,但不读取或写入自身。

回答by Miraage

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

file— 将整个文件读入一个数组
file_get_contents— 将整个文件读入一个字符串
fopen— 打开文件或 URL