PHP 檔案系統 file_get_contents() 函式



PHP 檔案系統 file_get_contents() 函式用於將檔案讀取到字串中。此函式是將檔案內容讀取到字串的首選方法,因為它可以利用記憶體對映技術(如果伺服器支援),從而提高效能。

此函式類似於 file() 函式,但 file_get_contents() 函式以字串形式返回檔案,從指定的偏移量開始,最多讀取 maxlen 位元組。

語法

以下是 PHP 檔案系統 file_get_contents() 函式的語法:

string file_get_contents ( string $filename [, bool $use_include_path = FALSE [, resource $context [, int $offset = 0 [, int $maxlen ]]]] )

引數

以下是 file_get_contents 函式的必選和可選引數:

序號 引數及描述
1

filename(必選)

要讀取的檔名。

2

use_include_path(可選)

布林值。如果設定為 true,則會在 include 路徑中搜索檔案。

3

context(可選)

此引數允許指定選項,例如超時、標頭等。

4

offset(可選)

要開始讀取檔案的起始位置。

5

maxlen(可選)

要讀取的最大位元組數。

返回值

它將檔案內容作為字串返回。如果失敗,則返回 FALSE。

PHP 版本

file_get_contents() 函式作為 PHP 4.3.0 的核心部分引入,並在 PHP 5、PHP 7、PHP 8 中都能很好地工作。

示例

在此示例中,我們將使用 PHP 檔案系統 file_get_contents() 函式讀取檔案並列印該檔案的內容。因此,這是此函式非常基本的用法。

<?php
   // Path to the file
   $file = file_get_contents("/PhpProject/sample.txt", true);

   echo $file;
?>

輸出

這將產生以下結果:

tutorialspoint
tutorix

示例

此 php 程式碼將向您展示如何使用 file_get_contents() 函式的可選引數並更改輸出內容。

  • 在此,我們使用了所有可選引數。
  • 第一個引數是檔案路徑。
  • 第二個和第三個引數(均為 NULL)是可選的,在此示例中未使用。
  • 第四個引數 - 4,是檔案中的起始位置。它將從第 4 個字元開始讀取。
  • 第五個引數 - 10,是要讀取的內容長度。它將讀取 10 個字元。
<?php
   // Define the file path here with optional parameters
   $section = file_get_contents("/PhpProject/sample.txt", NULL, NULL, 4, 10);
   var_dump($section);
?>

輸出

這將生成以下結果:

string(10) "rialspoint"

示例

在此 PHP 程式碼中,我們將瞭解如何處理檔案錯誤,例如,如果給定的檔案不存在於目錄中。因此,如果檔案不存在,我們可以向用戶顯示錯誤訊息。

<?php
   // Assign path of the file
   $file_path = "/Applications/XAMPP/xamppfiles/htdocs/mac/non_existent.txt";

   // Use file_get_contents() function to get the content
   $content = file_get_contents($file_path);

   // Check file exists or not
   if ($content === FALSE) {
      echo "Error: Unable to read the file at $file_path";
   } else {
      var_dump($content);
   }
?> 

輸出

這將產生以下結果:

Error: Unable to read the file at /Applications/XAMPP/xamppfiles/htdocs/mac/non_existent.txt

示例

在此示例中,我們的目標是使用給定的 URL(統一資源定位符)作為檔案,獲取其內容並將其回顯。

<?php
   // Reading a file from a URL
   $url = "https://www.example.com/sample.txt";

   // Get the content from the URL
   $content = file_get_contents($url);

   // Check the error 
   if ($content === FALSE) {
      echo "Error: Unable to read the file from the URL";
   } else {
      var_dump($content);
   }
?> 

輸出

這將導致以下結果:

string(102) "This is a sample url to check that it works!"

注意

必須正確處理故障,尤其是在處理可能無法訪問或不存在的檔案時。

總結

要將檔案的內容讀取到字串中,我們可以使用 PHP 的 file_get_contents() 函式。它能夠讀取整個檔案或僅讀取檔案的部分內容。該函式適用於基本的讀取檔案操作,但對於高效的操作,需要實現適當的錯誤處理。

php_function_reference.htm
廣告