(PHP 4, PHP 5, PHP 7, PHP 8)
fwrite — 寫(xiě)入文件(可安全用于二進(jìn)制文件)
$handle
, string $string
, int $length
= ?): int
fwrite() 把 string
的內容寫(xiě)入
文件指針 handle
處。
handle
文件系統指針,是典型地由 fopen() 創(chuàng )建的 resource(資源)。
string
The string that is to be written.
length
如果指定了
length
,當寫(xiě)入了
length
個(gè)字節或者寫(xiě)完了 string
以后,寫(xiě)入就會(huì )停止,視乎先碰到哪種情況。
注意如果給出了
length
參數,則 magic_quotes_runtime
配置選項將被忽略,而
string
中的斜線(xiàn)將不會(huì )被抽去。
fwrite() 返回寫(xiě)入的字符數,出現錯誤時(shí)則返回 false
。
注意:
Writing to a network stream may end before the whole string is written. Return value of fwrite() may be checked:
<?php
function fwrite_stream($fp, $string) {
for ($written = 0; $written < strlen($string); $written += $fwrite) {
$fwrite = fwrite($fp, substr($string, $written));
if ($fwrite === false) {
return $written;
}
}
return $written;
}
?>
注意:
在區分二進(jìn)制文件和文本文件的系統上(如 Windows) 打開(kāi)文件時(shí),fopen() 函數的 mode 參數要加上 'b'。
注意:
If
handle
was fopen()ed in append mode, fwrite()s are atomic (unless the size ofstring
exceeds the filesystem's block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock() a resource before calling fwrite(); all of the data will be written without interruption.
注意:
If writing twice to the file pointer, then the data will be appended to the end of the file content:
<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);
// the content of 'data.txt' is now 123 and not 23!
?>
示例 #1 一個(gè)簡(jiǎn)單的 fwrite() 例子
<?php
$filename = 'test.txt';
$somecontent = "添加這些文字到文件\n";
// 首先我們要確定文件存在并且可寫(xiě)。
if (is_writable($filename)) {
// 在這個(gè)例子里,我們將使用添加模式打開(kāi)$filename,
// 因此,文件指針將會(huì )在文件的末尾,
// 那就是當我們使用fwrite()的時(shí)候,$somecontent將要寫(xiě)入的地方。
if (!$handle = fopen($filename, 'a')) {
echo "不能打開(kāi)文件 $filename";
exit;
}
// 將$somecontent寫(xiě)入到我們打開(kāi)的文件中。
if (fwrite($handle, $somecontent) === FALSE) {
echo "不能寫(xiě)入到文件 $filename";
exit;
}
echo "成功地將 $somecontent 寫(xiě)入到文件$filename";
fclose($handle);
} else {
echo "文件 $filename 不可寫(xiě)";
}
?>