PHP file() 函數

定義和用法

file() 函數把整個文件讀入一個數組中。

file_get_contents() 類似,不同的是 file() 將文件作為一個數組返回。數組中的每個單元都是文件中相應的一行,包括換行符在內。

如果失敗,則返回 false。

語法

file(path,include_path,context)
參數 描述
path 必需。規定要讀取的文件。
include_path 可選。如果也想在 include_path 中搜尋文件的話,可以將該參數設為 "1"。
context

可選。規定文件句柄的環境。

context 是一套可以修改流的行為的選項。若使用 null,則忽略。

說明

context 的支持是 PHP 5.0.0 添加的。

返回的數組中每一行都包括了行結束符,因此如果不需要行結束符時還需要使用 rtrim() 函數。

提示和注釋

注釋:從 PHP 4.3.0 開始,可以用 file_get_contents() 來將文件讀入到一個字符串并返回。

注釋:從 PHP 4.3.0 開始,file() 可以安全用于二進制文件。

注釋:如果碰到 PHP 在讀取文件時不能識別 Macintosh 文件的行結束符,可以激活 auto_detect_line_endings 運行時配置選項。

實例

<?php
print_r(file("test.txt"));
?>

輸出:

Array
(
[0] => Hello World. Testing testing!
[1] => Another day, another line.
[2] => If the array picks up this line,
[3] => then is it a pickup line?
)