PHP中的file,file_get_contents和fopen之间的区别 [英] Difference between file, file_get_contents, and fopen in PHP

查看:138
本文介绍了PHP中的file,file_get_contents和fopen之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是PHP的新手,我不太确定:file()file_get_contents()fopen()函数之间有什么区别,何时应该在另一个之上使用?

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?

推荐答案

前两个 file file_get_contents 非常相似.他们都读取整个文件,但是file将该文件读取到一个数组中,而file_get_contents将该文件读取到一个字符串中. file返回的数组将由换行符分隔,但是每个元素仍将附加终止的换行符,因此您仍然需要注意这一点.

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.

fopen 函数的作用完全不同-它打开文件描述符,该文件描述符用作读取写入文件的流.它是一个低级的函数,是对C fopen函数的简单包装,并且仅调用fopen只会打开流.

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.

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

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.

所以,回顾一下:

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

这篇关于PHP中的file,file_get_contents和fopen之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆