PHP 檔案系統 fwrite() 函式



PHP 檔案系統fwrite()函式用於將內容寫入給定的檔案。要使用fwrite(),必須先開啟檔案。因此,您可以使用fopen()函式。

開啟檔案後,您可以使用fwrite()將文字或資料寫入其中。您提供檔案控制代碼(由fopen()返回的控制代碼)和要寫入的內容。寫入完成後,必須使用fclose()關閉檔案。

語法

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

fwrite ( resource $handle , string $string [, int $length ] ) : int|false

引數

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

序號 引數及描述
1

$handle(必需)

您要寫入的檔案。

2

$string(必需)

您要寫入檔案的內容。

3

$length(可選)

您要寫入的來自$string的位元組數。

返回值

fwrite()函式返回寫入檔案的位元組數,如果失敗則返回 FALSE。

PHP 版本

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

示例

我們在下面的程式碼中使用了 PHP 檔案系統fwrite()函式來寫入檔案。因此,檔案“myfile.txt”以寫入模式(“w”)開啟,使用fwrite()將內容“Hello, world!”寫入檔案,然後使用fclose()函式關閉檔案。

<?php
   // Open the file in writing mode
   $file = fopen("/PhpProjects/myfile.txt", "w");

   //Specify the content want to write
   $content = "Hello, world!";
   
   // Writes "Hello, world!" to the file
   fwrite($file, $content); 
   
   // Closes the file 
   fclose($file); 

   echo "The content is written successfully.";
?>

輸出

以下是以下程式碼的結果:

The content is written successfully.

示例

此 PHP 示例以追加模式開啟現有的檔案“myfile.txt”,向其中新增一些額外的文字內容,然後關閉檔案。

<?php
   // Open file in append mode
   $file = fopen("/PhpProjects/myfile.txt", "a");

   // Text to append
   $content = "This is an appended text.\n";

   // Append content to file
   fwrite($file, $content);

   // Close the file
   fclose($file);

   echo "Text appended to file.";
?> 

輸出

這將產生以下結果:

Text appended to file.

示例

在此 PHP 程式碼中,名為“binary_data.bin”的檔案以寫入模式開啟以寫入二進位制資料。使用pack()函式建立一些二進位制資料,然後寫入檔案。最後,關閉檔案。

<?php
   // Open file in write mode for binary data
   $file = fopen("binary_data.bin", "wb");

   // Binary data to write
   $data = pack("S*", 1990, 2024, 509, 1024);

   // Write binary data to file
   fwrite($file, $data);

   // Close the file
   fclose($file);

   echo "Binary data written to file.";
?> 

輸出

這將生成以下結果:

Binary data written to file.

注意

PHP 函式fwrite()在失敗時會引發 E_WARNING。

總結

fwrite()函式是 PHP 中用於檔案操作的功能強大的函式,用於各種目的,例如資料儲存、日誌記錄和動態內容生成。

php_function_reference.htm
廣告