查詢

file_get_contents()函式—用法及示例

「 將整個檔案讀入一個字串中 」


函式名稱:file_get_contents() 適用版本:PHP 4, PHP 5, PHP 7

函式描述:file_get_contents() 函式將整個檔案讀入一個字串中。

語法:string file_get_contents ( string $filename [, bool $use_include_path = FALSE [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )

引數:

  • $filename:要讀取的檔名。可以是本地檔案或 URL 地址。
  • $use_include_path(可選):如果設定為 TRUE,則檔案將從 include_path 中讀取。預設為 FALSE。
  • $context(可選):一個資源型別的上下文,用於指定不同的引數,如 HTTP 請求頭。更多資訊參見:http://php.net/manual/en/context.php
  • $offset(可選):從指定的偏移量開始讀取檔案。預設為 -1,表示從檔案的開頭讀取。
  • $maxlen(可選):讀取的最大位元組數。預設為讀取整個檔案。

返回值:返回包含檔案內容的字串,如果出錯則返回 FALSE。

示例:

  1. 讀取本地檔案:
$file_content = file_get_contents('path/to/file.txt');
echo $file_content;
  1. 讀取遠端檔案:
$url = 'https://example.com/data.txt';
$file_content = file_get_contents($url);
echo $file_content;
  1. 從指定偏移量開始讀取檔案:
$file_content = file_get_contents('path/to/file.txt', false, null, 10);
echo $file_content;

注意事項:

  • 當讀取大檔案時,可能會導致記憶體溢位,建議使用逐行讀取或其他方法處理大檔案。
  • 如果需要更復雜的檔案操作,如讀取檔案到陣列或寫入檔案,請考慮使用其他檔案處理函式,如 fopen()、fread()、fwrite() 等。
補充糾錯
上一個函式: file_put_contents()函式
下一個函式: file_exists()函式
熱門PHP函式
分享連結