函式名:fputs() 適用版本:PHP 4, PHP 5, PHP 7
函式描述:fputs() 函式用於將字串寫入開啟的檔案中。
用法: fputs ( resource $handle , string $string [, int $length ] ) : int
引數:
- $handle:必需,檔案資源型別的控制代碼,透過 fopen() 函式開啟檔案獲得。
- $string:必需,要寫入檔案的字串。
- $length:可選,指定要寫入的最大長度,預設為字串的長度。
返回值: 成功時返回寫入的位元組數,失敗時返回 false。
示例: <?php $filename = "example.txt"; $handle = fopen($filename, "w");
if ($handle) { $content = "Hello, World!"; $bytes_written = fputs($handle, $content);
if ($bytes_written === false) { echo "寫入檔案失敗"; } else { echo "成功寫入 $bytes_written 位元組"; }
fclose($handle); } else { echo "無法開啟檔案"; } ?>
在上述示例中,我們首先使用 fopen() 函式開啟一個檔案,然後使用 fputs() 函式將字串 "Hello, World!" 寫入檔案。最後,使用 fclose() 函式關閉檔案控制代碼。如果寫入成功,將輸出成功寫入的位元組數;如果寫入失敗,將輸出錯誤資訊。