readfile()
是 PHP 中的一個內置函數,用于從服務器讀取文件并將其作為字符串輸出。這個函數非常適合在處理文本文件時使用,因為它可以方便地讀取文件內容并以純文本格式返回。
以下是使用 readfile()
函數處理文本文件的示例:
example.txt
的文本文件,并在其中添加一些內容:Hello, World!
This is an example text file.
readfile()
函數讀取并輸出 example.txt
文件的內容:<?php
// 設置要讀取的文件路徑
$file_path = 'example.txt';
// 使用 readfile() 函數讀取文件內容
$file_content = readfile($file_path);
// 輸出文件內容
echo $file_content;
?>
當你在瀏覽器中運行此 PHP 腳本時,它將輸出 example.txt
文件的內容,如下所示:
Hello, World!
This is an example text file.
readfile()
函數簡單且易于使用,但在處理大文件時可能會遇到性能問題。在這種情況下,可以考慮使用 file()
函數或 fopen()
、fgets()
等函數逐行讀取文件內容。