📜  PHP-文件和I / O

📅  最后修改于: 2020-10-21 05:09:17             🧑  作者: Mango


本章将解释与文件有关的以下功能-

  • 开启档案
  • 读取文件
  • 写文件
  • 关闭档案

打开和关闭文件

PHP fopen()函数用于打开文件。它需要两个参数,首先说明文件名,然后说明操作方式。

可以将文件模式指定为此表中的六个选项之一。

Sr.No Mode & Purpose
1

r

Opens the file for reading only.

Places the file pointer at the beginning of the file.

2

r+

Opens the file for reading and writing.

Places the file pointer at the beginning of the file.

3

w

Opens the file for writing only.

Places the file pointer at the beginning of the file.

and truncates the file to zero length. If files does not

exist then it attempts to create a file.

4

w+

Opens the file for reading and writing only.

Places the file pointer at the beginning of the file.

and truncates the file to zero length. If files does not

exist then it attempts to create a file.

5

a

Opens the file for writing only.

Places the file pointer at the end of the file.

If files does not exist then it attempts to create a file.

6

a+

Opens the file for reading and writing only.

Places the file pointer at the end of the file.

If files does not exist then it attempts to create a file.

如果尝试打开文件失败,则fopen返回false值,否则返回文件指针,该指针用于进一步读取或写入该文件。

对打开的文件进行更改之后,使用fclose()函数将其关闭很重要。 fclose()函数需要一个文件指针作为其参数,然后在关闭成功时返回true ,或者在关闭失败时返回false

读取文件

使用fopen()函数打开文件后,即可使用名为fread()的函数读取该文件。此函数需要两个参数。这些必须是文件指针,文件的长度以字节为单位。

可以使用filesize()函数找到文件长度,该函数将文件名作为其参数,并返回以字节为单位的文件大小。

因此,这是使用PHP读取文件所需的步骤。

  • 使用fopen()函数打开文件。

  • 使用filesize()函数获取文件的长度。

  • 使用fread()函数读取文件的内容。

  • 使用fclose()函数关闭文件。

以下示例将文本文件的内容分配给变量,然后将这些内容显示在网页上。

Reading a file using PHP
   
   
   
      
      $filetext

它将产生以下结果-

读取文件

写文件

使用PHP fwrite()函数可以编写新文件或将文本附加到现有文件。该函数需要两个参数来指定文件指针和要写入的数据字符串。可选地,可以包括第三个整数参数,以指定要写入的数据的长度。如果包含第三个参数,则在达到指定的长度后,写入将停止。

下面的示例创建一个新的文本文件,然后在其中写入一个简短的文本标题。关闭此文件后,使用file_exist()函数确认该文件的存在,该函数将文件名作为参数



   
   
      Writing a file using PHP
   
   
   
      
      
      
   

它将产生以下结果-

写文件

我们已经覆盖了所有的有关文件输入和出函数PHP文件系统功能的篇章。