(PHP 4 >= 4.3.0, PHP 5)
file_get_contents — 將整個文件讀入一個字符串
說明
string file_get_contents ( string$filename
[, bool $use_include_path
= false
[, resource $context
[, int $offset
= -1
[, int $maxlen
]]]] )
和 file() 一樣,只除了
file_get_contents() 把文件讀入一個字符串。將在參數
offset
所指定的位置開始讀取長度為
maxlen
的內容。如果失敗,file_get_contents()
將返回 FALSE
。
file_get_contents() 函數是用來將文件的內容讀入到一個字符串中的首選方法。如果操作系統支持還會使用內存映射技術來增強性能。
Note:
如果要打開有特殊字符的 URL (比如說有空格),就需要使用 urlencode() 進行 URL 編碼。
參數
filename
要讀取的文件的名稱。
use_include_path
Note:
As of PHP 5 the FILE_USE_INCLUDE_PATH
can be used
to trigger include path
search.
context
A valid context resource created with
stream_context_create().
如果你不需要自定義 context,可以用 NULL
來忽略。
offset
The offset where the reading starts on the original stream.
Seeking (offset
) is not supported with remote files.
Attempting to seek on non-local files may work with small offsets, but this
is unpredictable because it works on the buffered stream.
maxlen
Maximum length of data read. The default is to read until end of file is reached. Note that this parameter is applied to the stream processed by the filters.
返回值
The function returns the read data 或者在失敗時返回 FALSE
.
錯誤/異常
An E_WARNING
level error is generated if either maxlength
is less than zero, or if seeking to the specified offset
in the stream fails.
范例
Example #1 Get and output the source of the homepage of a website
<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>
Example #2 Searching within the include_path
<?php
// <= PHP 5
$file = file_get_contents('./people.txt', true);
// > PHP 5
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>
Example #3 Reading a section of a file
<?php
// Read 14 characters starting from the 21st character
$section = file_get_contents('./people.txt', NULL, NULL, 20, 14);
var_dump($section);
?>
以上例程的輸出類似于:
string(14) "lle Bjori Ro"
Example #4 Using stream contexts
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: enrn" .
"Cookie: foo=barrn"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>
更新日志
版本
說明
5.1.0
Added the offset
and
maxlen
parameters.
5.0.0
Added context support.
注釋
Note: 此函數可安全用于二進制對象。
Tip如已啟用fopen 包裝器,在此函數中, URL 可作為文件名。關于如何指定文件名詳見 fopen()。各種 wapper 的不同功能請參見 支持的協議和封裝協議,注意其用法及其可提供的預定義變量。
Warning使用 SSL 時,Microsoft IIS 會違反協議不發送close_notify標記就關閉連接。PHP 會在到達數據尾端時報告“SSL: Fatal Protocol Error”。 要解決此問題,error_reporting 應設定為降低級別至不包含警告。 PHP 4.3.7 及更高版本可以在使用 https:// 包裝器打開流時檢測出有問題的 IIS 服務器軟件 并抑制警告。在使用 fsockopen() 創建 ssl:// 套接字時, 開發者需檢測并抑制此警告。
參見
file() - 把整個文件讀入一個數組中 fgets() - 從文件指針中讀取一行 fread() - 讀取文件(可安全用于二進制文件) readfile() - 輸出一個文件 file_put_contents() - 將一個字符串寫入文件 stream_get_contents() - 讀取資源流到一個字符串 stream_context_create() - 創建資源流上下文 $http_response_header