(PHP 4, PHP 5, PHP 7, PHP 8)
fwrite — 写入文件(可安全用于二进制文件)
$handle, string $string, int $length = ?): int
   fwrite() 把 string 的内容写入
   文件指针 handle 处。 
  
handle文件系统指针,是典型地由 fopen() 创建的 resource(资源)。
stringThe string that is to be written.
length
       如果指定了
   length,当写入了
   length 个字节或者写完了 string
   以后,写入就会停止,视乎先碰到哪种情况。
      
        注意如果给出了
   length
   参数,则 magic_quotes_runtime
   配置选项将被忽略,而
   string 中的斜线将不会被抽去。
      
   fwrite() 返回写入的字符数,出现错误时则返回 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;
}
?>
注意:
在区分二进制文件和文本文件的系统上(如 Windows) 打开文件时,fopen() 函数的 mode 参数要加上 'b'。
注意:
If
handlewas fopen()ed in append mode, fwrite()s are atomic (unless the size ofstringexceeds 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 一个简单的 fwrite() 例子
<?php
$filename = 'test.txt';
$somecontent = "添加这些文字到文件\n";
// 首先我们要确定文件存在并且可写。
if (is_writable($filename)) {
    // 在这个例子里,我们将使用添加模式打开$filename,
    // 因此,文件指针将会在文件的末尾,
    // 那就是当我们使用fwrite()的时候,$somecontent将要写入的地方。
    if (!$handle = fopen($filename, 'a')) {
         echo "不能打开文件 $filename";
         exit;
    }
    // 将$somecontent写入到我们打开的文件中。
    if (fwrite($handle, $somecontent) === FALSE) {
        echo "不能写入到文件 $filename";
        exit;
    }
    echo "成功地将 $somecontent 写入到文件$filename";
    fclose($handle);
} else {
    echo "文件 $filename 不可写";
}
?>