函式名稱:fprintf()
適用版本:所有版本的 PHP
函式描述:fprintf() 函式將格式化的字串寫入到指定的檔案中。
語法:fprintf(file, format, arg1, arg2, ...)
引數:
- file:必需,指定要寫入的檔案。
- format:必需,指定要寫入的格式化字串。
- arg1, arg2, ...:可選,指定要插入到格式化字串中的引數。
返回值:成功時返回寫入的字元數,失敗時返回 false。
示例:
$file = fopen("test.txt", "w");
if ($file) {
$name = "John";
$age = 25;
$result = fprintf($file, "My name is %s and I am %d years old.", $name, $age);
if ($result !== false) {
echo "寫入成功,寫入了 " . $result . " 個字元。";
} else {
echo "寫入失敗。";
}
fclose($file);
} else {
echo "無法開啟檔案。";
}
以上示例中,我們開啟一個名為 "test.txt" 的檔案,並使用 fprintf() 函式將格式化的字串寫入到該檔案中。格式化字串 "My name is %s and I am %d years old." 中的 %s 和 %d 分別表示字串和整數的佔位符,而 $name 和 $age 則是要插入到格式化字串中的引數。最後,我們透過檢查 fprintf() 函式的返回值來確定寫入是否成功,並輸出相應的資訊。最後,我們關閉了檔案控制代碼。