导航首页 » 技术教程 » PHP:file()的用法_Filesystem函数
PHP:file()的用法_Filesystem函数 139 2023-12-15   

file

(PHP 4, PHP 5)

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

说明

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

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

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:// 套接字时, 开发者需检测并抑制此警告。

参见

readfile() - 输出一个文件 fopen() - 打开文件或者 URL fsockopen() - 打开一个网络连接或者一个Unix套接字连接 popen() - 打开进程文件指针 file_get_contents() - 将整个文件读入一个字符串 include - include stream_context_create() - 创建资源流上下文


!!!站长长期在线接!!!

网站、小程序:定制开发/二次开发/仿制开发等

各种疑难杂症解决/定制接口/定制采集等

站长微信:lxwl520520

站长QQ:1737366103