目录

PHP fopen() 函数

❮ PHP 文件系统参考

示例

打开文件,读取行 - 直到到达 EOF:

<?php
$file = fopen("test.txt", "r");

//Output lines until EOF is reached
while(! feof($file)) {
  $line = fgets($file);
  echo $line. "<br>";
}

fclose($file);
?>
运行示例 »

定义和用法

fopen() 函数打开文件或 URL。

笔记:写入文本文件时,请务必使用正确的行结束字符! Unix 系统使用 \n,Windows 系统使用 \r\n,Macintosh 系统使用 \r 作为行结束符。 Windows 提供了一个转换标志 ('t'),在处理文件时会将 \n 转换为 \r\n。您还可以使用“b”强制二进制模式。要使用这些标志,请将“b”或“t”指定为模式参数的最后一个字符。

语法

fopen( filename, mode, include_path, context)

参数值

Parameter Description
filename Required. Specifies the file or URL to open
mode Required. Specifies the type of access you require to the file/stream.

Possible values:

  • "r" - Read only. Starts at the beginning of the file
  • "r+" - Read/Write. Starts at the beginning of the file
  • "w" - Write only. Opens and truncates the file; or creates a new file if it doesn't exist. Place file pointer at the beginning of the file
  • "w+" - Read/Write. Opens and truncates the file; or creates a new file if it doesn't exist. Place file pointer at the beginning of the file
  • "a" - Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist
  • "a+" - Read/Write. Preserves file content by writing to the end of the file
  • "x" - Write only. Creates a new file. Returns FALSE and an error if file already exists
  • "x+" - Read/Write. Creates a new file. Returns FALSE and an error if file already exists
  • "c" - Write only. Opens the file; or creates a new file if it doesn't exist. Place file pointer at the beginning of the file
  • "c+" - Read/Write. Opens the file; or creates a new file if it doesn't exist. Place file pointer at the beginning of the file
  • "e" - Only available in PHP compiled on POSIX.1-2008 conform systems.
include_path Optional. Set this parameter to '1' if you want to search for the file in the include_path (in php.ini) as well
context Optional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream


技术细节

返回值: 成功时为文件指针资源,失败时为 FALSE 和错误。您可以通过在函数名称前面添加 "@" 来隐藏错误。
PHP 版本: 4.3+
PHP 变更日志: PHP 7.1:添加了 "e" 选项
PHP 5.2:添加了 "c" 和 "c+" 选项

❮ PHP 文件系统参考