(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() - 創建資源流上下文