fwrite($handle, $string, $length = null);
$handle:fopen() 回傳的檔案控制代碼$string:要寫入的字串$length:可選,最大寫入位元組數回傳寫入的位元組數,失敗回傳 false。
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);
檔案內容將為:
Bobby Bopper Tracy Tanner
w / w+:清空檔案後從頭寫入a / a+:從檔案末尾追加寫入r+:從頭寫入但不清空,會覆蓋現有內容$fh = fopen("testFile.txt", 'w') or die("can't open file");
fwrite($fh, "Floppy Jalopy\n");
fwrite($fh, "Pointy Pinto\n");
fclose($fh);
原內容完全被取代。
$fh = fopen("counter.txt", 'c+'); // 開啟讀寫,不存在則建立
if (flock($fh, LOCK_EX)) { // 獨佔鎖定
$count = (int)fread($fh, filesize("counter.txt"));
$count++;
ftruncate($fh, 0); // 清空
rewind($fh); // 指標回開頭
fwrite($fh, (string)$count);
flock($fh, LOCK_UN); // 釋放鎖定
}
fclose($fh);
$data = pack("C*", 0x48, 0x65, 0x6C, 0x6C, 0x6F); // "Hello"
$fh = fopen("binary.dat", 'wb');
fwrite($fh, $data);
fclose($fh);
fwrite 回傳值是否為 false 或小於預期長度fflush() 強制刷新緩衝區