PHP 檔案系統 fgets() 函式



PHP 檔案系統fgetcsv()函式用於從開啟的檔案中返回一行。此函式在指定長度的新行或檔案結尾處停止返回,以先到者為準,並在失敗時返回false。

呼叫函式時指定的長度引數允許它從檔案中讀取最多length-1個位元組。

當您想逐行處理檔案時,例如處理文字檔案或日誌檔案時,它非常有用。

語法

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

string fgets ( resource $handle [, int $length ] )

引數

以下是fgets()函式的必需和可選引數:

序號 引數及描述
1

handle(必需)

這是一個檔案指標資源,指向您要從中讀取的檔案。

2

length(可選)

指定要讀取行的最大長度。如果省略,它將讀取到下一個換行符。

返回值

fgets()函式返回包含從檔案中讀取行的字串。如果發生錯誤或到達檔案結尾,則返回false。

PHP 版本

fgets()函式最初作為核心PHP 4的一部分引入,並與PHP 5、PHP 7、PHP 8良好相容。

示例

此PHP程式碼將使用PHP檔案系統fgetcsv()函式讀取給定檔案的首行。因此,我們將讀取sample.txt檔案的首行。

以下是此示例的簡單演示:

<?php
   $file = fopen("/PhpProject/sample.txt", "r");
   echo fgets($file);
   fclose($file);
?>

輸出

這將產生以下結果:

tutorialspoint

示例

此PHP程式碼將使用fgets()函式讀取給定的整個檔案。因此,我們將在這裡讀取sample.txt檔案。

<?php
   $file = fopen("/PhpProject/sample.txt", "r");
 
   while(! feof($file)) {
      echo fgets($file). "\n";
   }
 
   fclose($file);
?>

輸出

這將生成以下結果:

tutorialspoint

tutorix

示例

現在,我們將嘗試使用PHP中的fgets()函式讀取特定數量的字元。此外,我們將使用substr()函式從給定檔案中建立子字串。然後在轉到下一行之前輸出每一行的前5個字元。

<?php
   // Open the file in read mode
   $file = fopen("/Applications/XAMPP/xamppfiles/htdocs/mac/newfile.txt", "r");

   while (($line = fgets($file)) !== false) { // Loop until end of file
      // Read and output first 5 characters of each line
      echo substr($line, 0, 5) . "<br>";
   }
   fclose($file); // Close the file
?> 

輸出

這將建立以下結果:

Hello
Tutor
Tutor
Compu
Infor

示例

使用以下程式碼,您可以藉助PHP中的fgets()函式跳過空行。讓我們看看它是如何工作的。

<?php
   // Open the file in read mode
   $file = fopen("/Applications/XAMPP/xamppfiles/htdocs/mac/newfile.txt", "r");

   // Loop until end of file
   while (($line = fgets($file)) !== false) { 
      // Remove leading and trailing whitespace
      $trimmed_line = trim($line); 
      // Check if line is not empty
      if (!empty($trimmed_line)) { 
         // Output the line
         echo $trimmed_line . "<br>"; 
      }
   }
   fclose($file); // Close the file
?> 

輸出

Hello
Tutorialspoint
Tutorix
Computer Science
Information

注意

請記住,在使用PHPfgets()函式之前,必須使用fopen()方法檢索檔案控制代碼($handle)。確保在讀取檔案後使用fclose()關閉檔案控制代碼以節省系統資源。

總結

在PHP中,fgets()函式可以讀取檔案中的一行。逐行處理檔案在處理文字檔案或日誌檔案時非常有用。

php_function_reference.htm
廣告