PHP 檔案系統 fputs() 函式



PHP 檔案系統fputs()函式用於寫入已開啟的檔案。此函式可以在檔案末尾或達到指定長度時停止,以先到達者為準。此函式在成功時返回寫入的位元組數,失敗時返回 false。此函式的功能與 fwrite() 函式類似。

此函式是二進位制安全的,這意味著可以使用此函式寫入影像等二進位制資料和字元資料。

語法

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

fputs(file, string, length)

引數

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

序號 引數及說明
1

filepath (必需)

將要掃描的目錄。

2

string (必需)

要寫入的內容。

返回值

成功時返回寫入的位元組數,失敗時返回 FALSE。

PHP 版本

fputs()函式最初作為 PHP 4 核心的一部分引入,並能很好地與 PHP 5、PHP 7、PHP 8 協同工作。

示例

在這個示例中,我們將看到如何使用 PHP 檔案系統fputs()函式將內容寫入給定檔案。

<?php
   // Path to the file and open it
   $file = fopen("/PhpProject1/sample.txt", "w");

   // Write to an open file
   echo fputs($file, "Hello Tutorialspoint!!!!");

   // Close the file
   fclose($file);
?>

輸出

以下是上述 PHP 示例的輸出:

24

示例

在這個示例中,我們將把陣列的內容寫入檔案。當您想要儲存組織好的資料(例如專案列表)時,這很有用。

每個專案都使用fputs()寫入檔案,每個專案後面都追加一個換行符。

<?php
   // Define an array of items
   $dataArray = ["Item 1", "Item 2", "Item 3"]; 

   // Open "example3.txt" for writing
   $file = fopen("myfile.txt", "w"); 

   // Check if the file was opened successfully
   if ($file) { 
      // Loop through each item in the array
      foreach ($dataArray as $item) {
         // Write each item to the file with a newline 
         fputs($file, $item . "<br>"); 
      }
      // Close the file
      fclose($file); 
      echo "Array written successfully to myfile.txt.";
   } else {
      echo "Unable to open example3.txt.";
   }
?> 

輸出

這將生成以下結果:

Array written successfully to myfile.txt.

示例

此示例演示如何將多行文字寫入檔案。當您需要記錄訊息或事件時,這很有用。這裡使用fputs()函式將每個日誌訊息寫入檔案。

<?php
   // Define an array of log messages
   $logMsgs = [
      "Log entry 1: User logged in.",
      "Log entry 2: User updated profile.",
      "Log entry 3: User logged out."
   ]; 

   // Open "myfile.txt" for appending
   $file = fopen("myfile.txt", "a"); 

   // Check if the file was opened successfully
   if ($file) { 
      
      // Loop through each log message
      foreach ($logMsgs as $message) { 
         
         // Write each message to the file with a newline
         fputs($file, $message . "<br>"); 
      }
      fclose($file); // Close the file
      echo "Log messages written successfully to myfile.txt.";
   } else {
      echo "Unable to open myfile.txt.";
   }
?> 

輸出

這將導致以下結果:

Log messages written successfully to myfile.txt.

注意

在嘗試寫入檔案之前,每次都要確保檔案已成功開啟。這可以防止在無法開啟檔案時發生錯誤。

為了在寫入後始終關閉檔案,請使用 fclose()。這可以保證所有資源都被釋放,並且資料被正確儲存。

總結

PHP 的fputs()函式用於將資料寫入檔案。示例顯示瞭如何在各種場景下使用fputs()將各種型別的資料寫入檔案。正確的檔案處理允許安全有效地寫入資料。

php_function_reference.htm
廣告