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
Difference between file, file_get_contents, and fopen in PHP
提问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, 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.
前两个,file
和file_get_contents
非常相似。它们都读取整个文件,但file
将文件读入数组,同时file_get_contents
将其读入字符串。返回的数组file
将由换行符分隔,但每个元素仍会附加终止换行符,因此您仍然需要注意这一点。
The fopen
function 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 fopen
function, and simply calling fopen
won'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 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.
打开文件句柄后,您可以使用其他函数(如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 arrayfile_get_contents
— Reads entire file into a stringfopen
— Opens file or URL
file
— 将整个文件读入一个数组file_get_contents
— 将整个文件读入一个字符串fopen
— 打开文件或 URL