| 函數/方法 | 返回類型 | 適用場景 | 性能/特點 |
|---|---|---|---|
fread() | string | 二進制/大文件、需控制讀取長度、流式讀取 | 底層控制力最強,需手動 fopen/fclose |
fgets() | string(單行) | 逐行處理大文本(日志、CSV) | 內存友好,默認 1KB 行長 |
fgetss() | string(單行) | 逐行讀取並剝離 HTML/PHP 標籤 | 可保留指定標籤,解析類文本 |
file() | array(行數組) | 小/中型文本整體讀入、需隨機訪問行 | 自動處理換行,含換行符 |
readfile() | int(字節數) | 直接輸出文件到瀏覽器(下載、圖片代理) | 不經 PHP 內存緩衝,極快 |
file_get_contents() | string | 全文讀入字符串、支援流上下文(超時、Header) | 性能優於 fopen 系,首選通用讀取 |
fpassthru() | int(字節數) | 從當前指針位置輸出剩餘內容到瀏覽器 | 配合 fseek 實現斷點續傳/分片輸出 |
parse_ini_file() | array(結構化) | 解析 INI 配置文件,支援節 | 專用場景,自動類型轉換 |
<?php
// 本地文件:一次性讀取
$handle = fopen('/usr/local/something.txt', 'rb'); // 二進制模式
$contents = fread($handle, filesize('/usr/local/something.txt'));
fclose($handle);
// 遠程/流文件:分塊循環讀取(無 filesize)
$handle = fopen('https://www.baidu.com', 'r');
$content = '';
while (!feof($handle)) {
$content .= fread($handle, 8192);
}
fclose($handle);
// 或利用 fread 返回 false 判斷結束
while (false !== ($chunk = fread($handle, 8192))) {
$content .= $chunk;
}
?>
<?php
$handle = fopen('./file.txt', 'r');
while (!feof($handle)) {
echo fgets($handle, 1024); // 保留換行符
}
fclose($handle);
// fgetss: 自動去除標籤,第三參數保留允許標籤
$handle = fopen('./file.txt', 'r');
while (!feof($handle)) {
echo fgetss($handle, 1024, '<br><p>');
}
fclose($handle);
?>
<?php
$lines = file('./file.txt');
foreach ($lines as $num => $line) {
echo "Line " . ($num + 1) . ": " . rtrim($line) . "<br>";
}
?>
<?php
$size = readfile('./file.txt'); // 直接輸出到瀏覽器
echo "Transferred $size bytes";
?>
<?php
// 基本用法
$content = file_get_contents('./file.txt');
// 遠程請求帶超時上下文
$ctx = stream_context_create([
'http' => [
'timeout' => 5, // 秒
'header' => "User-Agent: MyApp/1.0\r\n"
]
]);
$content = file_get_contents('https://api.example.com/data', 0, $ctx);
?>
性能提示:file_get_contents 內部使用內存映射(mmap),大文件讀取顯著快於 fopen/fread 組合。readfile 直接輸出無內存佔用,極適合大文件下載代理。
<?php
header('Content-Type: text/html; charset=utf-8');
$handle = fopen('./test2.php', 'r');
fseek($handle, 1024); // 跳過前 1KB
fpassthru($handle); // 輸出剩餘
?>
test.ini:
; 註釋 [first_section] one = 1 five = 5 animal = BIRD [second_section] path = "/usr/local/bin" URL = "https://www.example.com/~username"
test.php:
<?php
$config = parse_ini_file('./test.ini', true); // true = 解析節
print_r($config);
/* 輸出:
Array
(
[first_section] => Array([one]=>1 [five]=>5 [animal]=>BIRD)
[second_section] => Array([path]=>/usr/local/bin [URL]=>https://...)
)
*/
?>
b 標志:fopen($file, 'rb'),跨平台兼容(Windows 必須,Linux 無害);php.ini 級別,生產建議 Off;fopen('https://example.com/'.urlencode($path));fread 分塊或 readfile 直接輸出,避免 file_get_contents 撐爆內存。