网 logo

PHP File

PHP file() 函数把整个文件读入一个数组中。与 File_get_contents() 类似,不同的是 file() 将文件作为一个数组返回。数组中的每个单元都是文件中相应的一行,包括换行符在内。如果失败,则返回 false。

语法

说明

对context 的支持是 PHP 5.0.0 添加的。

返回的数组中每一行都包括了行结束符,因此如果不需要行结束符时还需要使用 rtrim() 函数。

提示和注释

注释:从 PHP 4.3.0 开始,可以用 file_get_contents() 来将文件读入到一个字符串并返回。

注释:从 PHP 4.3.0 开始,File() 可以安全用于二进制文件。

注释:如果碰到 PHP 在读取文件时不能识别 麦金塔 文件的行结束符,可以激活 auto_detect_line_endings 运行时配置选项。

例子

输出:

实例

读取远程文件

\u003c?php

// Get a file into an array. In this Example we'll go through HTTP to get

// the HTML source of a URL.

= file('读取网址');

// Loop through our array, show HTML source as HTML source; and line numbers too.

foreach ( as =\u003e ) {

echo "Line #\u003cb\u003e\u003c/b\u003e : " . htmlspecialchars() . "\u003cbr /\u003en";

}

// Another Example, let's get a web page into a string. See also file_get_contents().

$HTML = implode('', file(‘读取网址'));

// Using the optional flags parameter since PHP 5

= file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

?\u003e

PHP Filesystem 函数

参考资料