PHP 檔案系統 file_put_contents() 函式



PHP 檔案系統file_put_contents()函式用於將資料寫入檔案。這是一種簡單易用的資料儲存方法。該函式將資料寫入檔案。如果當前檔案不存在,它將建立一個新檔案。如果檔案已存在,預設情況下它將被替換。

語法

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

int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )

引數

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

序號 引數及描述
1

filename(必需)

您要寫入的檔名。

2

data(必需)

您要寫入的資料。

3

flags(可選)

附加選項。例如,您可以新增 FILE_APPEND 將資料新增到檔案的末尾。

4

context(可選)

上下文資源。

返回值

如果成功,該函式將返回寫入檔案的字元數。如果失敗,它將返回 false。

PHP 版本

file_put_contents()函式作為 PHP 5 核心的一部分提供,並且與 PHP 7、PHP 8 良好相容。

示例

在下面的示例中,我們將使用 PHP 檔案系統file_put_contents()函式並將一些內容寫入給定檔案。為此,我們必須輸入檔案路徑以及我們要使用file_put_contents()函式寫入給定檔案的內容。

<?php
   echo file_put_contents("PhpProject/sample.txt" ,"Hello World!");
?> 

輸出

11

示例

以下程式碼的方法是使用file_put_contents()函式將內容追加到給定的文字檔案中。我們使用了 FILE_APPEND 標誌將內容新增到檔案的末尾,並使用 LOCK_EX 標誌來防止其他人同時寫入檔案。

<?php
   $file = "/PhpProject1/sample.txt";
   
   // The new person to add to the file
   $test = " Tutorialspoint";

   // using the FILE_APPEND and LOCK_EX flag
   file_put_contents($file, $test, FILE_APPEND | LOCK_EX);
   
   echo "Content has been loaded successfully";
?>

輸出

這將產生以下結果:

Content has been loaded successfully

示例

下面的 PHP 程式碼將使用file_put_contents()函式將陣列元素寫入給定的文字檔案,每個元素都在新的一行。該程式碼還使用 implode() 函式將陣列的項連線成單個字串。

<?php
   // array to write in the text file
   $data = array('First line', 'Second line', 'Third line');

   // 
   echo file_put_contents('/PhpProject1/sample.txt', implode("\n", $data));
?> 

輸出

這將生成以下結果:

First line
Second line
Third line

示例

在下面的 PHP 程式碼中,我們將嘗試建立一個非文字檔案並將提供的資料寫入該檔案。因此,這段程式碼將基本寫入內容(如果檔案可用)並顯示成功訊息。

<?php
   // add the data here to be added in the file
   $content = 'echo "Hello World!";';

   // Writing content to file
   file_put_contents('/Applications/XAMPP/xamppfiles/htdocs/mac/newfile.php', $content);

   // Check if the file is written successfully
   if (file_exists('newfile.php')) {
      echo 'File created successfully.';
   } else {
      echo 'Error creating file.';
   }
?> 

輸出

這將建立以下結果:

File created successfully.

注意

務必確保file_put_contents()方法中給出的檔案路徑準確無誤,並且具有必要的寫入許可權。

總結

在這個例子中,我們向您解釋瞭如何建立一個新檔案並使用file_put_contents()函式向其中寫入內容。此外,我們檢查了檔案生成是否成功並提供了必要的說明。

php_function_reference.htm
廣告