fwrite()
向文件句柄写入内容,可指定写入长度。
fwrite(resource $stream, string $data, ?int $length = null): int|false
参数
| 参数 | 类型 | 说明 |
|---|---|---|
$stream | resource | 已打开的文件句柄 |
$data | string | 要写入的内容 |
$length | ?int | 最多写多少字节 |
返回值
int|false — 实际写入的字节数,失败返回 false。
示例
$fh = fopen('out.txt', 'w');
fwrite($fh, "第一行\n");
fwrite($fh, "第二行\n");
fclose($fh);注意
- 返回值可能小于 strlen($data)(比如磁盘满),关键写入要检查。
- 用 a 模式打开是追加,w 模式会清空原文件。
- 大文件分块写时,每块写完后可 fflush 控制刷盘频率。