Php/docs/function.file

来自菜鸟教程
跳转至:导航、​搜索

file

(PHP 4, PHP 5, PHP 7)

file把整个文件读入一个数组中


说明

file ( string $filename [, int $flags = 0 [, resource $context ]] ) : array

把整个文件读入一个数组中。

Note:

你可以通过 file_get_contents() 以字符串形式获取文件的内容。

参数

filename

文件的路径。

Tip

如已启用fopen 包装器,在此函数中, URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议,注意其用法及其可提供的预定义变量。

flags

可选参数 flags 可以是以下一个或多个常量:

FILE_USE_INCLUDE_PATH
include_path 中查找文件。
FILE_IGNORE_NEW_LINES
在数组每个元素的末尾不要添加换行符
FILE_SKIP_EMPTY_LINES
跳过空行
context

A context resource created with the stream_context_create() function.

Note: 在 PHP 5.0.0

中增加了对上下文(Context)的支持。有关上下文(Context)的说明参见

Streams


返回值

Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns false.

Note:

Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used, so you still need to use rtrim() if you do not want the line ending present.

Note:

在读取在 Macintosh 电脑中或由其创建的文件时, 如果 PHP

不能正确的识别行结束符,启用运行时配置可选项 auto_detect_line_endings 也许可以解决此问题。

更新日志

版本 说明
5.0.0 增加了参数 context
5.0.0 Prior to PHP 5.0.0 the flags parameter only

covered include_path and was enabled with 1

4.3.0 file() 开始是二进制安全的


范例

Example #1 file() 例子

<?php// 将一个文件读入数组。本例中通过 HTTP 从 URL 中取得 HTML 源文件。$lines = file('http://www.example.com/');// 在数组中循环,显示 HTML 的源文件并加上行号。foreach ($lines as $line_num => $line) {    echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";}// 另一个例子将 web 页面读入字符串。参见 file_get_contents()。$html = implode(, file('http://www.example.com/'));// 从 PHP 5 开始可以使用可选标记参数$trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);?>

注释

Warning 使用 SSL 时,Microsoft IIS 会违反协议不发送close_notify标记就关闭连接。PHP 会在到达数据尾端时报告“SSL: Fatal Protocol Error”。 要解决此问题,error_reporting 应设定为降低级别至不包含警告。 PHP 4.3.7 及更高版本可以在使用 https:// 包装器打开流时检测出有问题的 IIS 服务器软件 并抑制警告。在使用 fsockopen() 创建 ssl:// 套接字时, 开发者需检测并抑制此警告。


参见