Difference between file, file_get_contents, and fopen in PHP

后端 未结 2 755
礼貌的吻别
礼貌的吻别 2020-12-02 20:57

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 w

相关标签:
2条回答
  • 2020-12-02 21:04

    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.
    0 讨论(0)
  • 2020-12-02 21:22

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

    0 讨论(0)
提交回复
热议问题