PHP fwrite 函数
最后修改于 2025 年 4 月 3 日
PHP fwrite
函数用于将数据写入文件。它是 PHP 中进行文件操作的基础函数。本教程将深入介绍其用法。
基本定义
fwrite
函数向已打开的文件写入数据。它需要一个文件句柄和要写入的字符串。一个可选的长度参数可以限制写入的字节数。
语法:fwrite(resource $handle, string $data, int $length = ?): int
。它返回写入的字节数,如果失败则返回 false。
基本的 fwrite 示例
这展示了 fwrite
写入文件的最简单用法。
basic_fwrite.php
<?php declare(strict_types=1); $file = fopen("example.txt", "w"); if ($file) { $bytes = fwrite($file, "Hello, World!"); fclose($file); echo "Wrote $bytes bytes to file."; } else { echo "Failed to open file."; }
这将创建“example.txt”文件,并向其中写入“Hello, World!”。始终检查 fopen 是否成功,并在完成后关闭文件。该函数返回写入的字节数。
追加到文件
使用“a”模式将数据附加到现有文件,而不会覆盖。
append_fwrite.php
<?php declare(strict_types=1); $file = fopen("example.txt", "a"); if ($file) { $bytes = fwrite($file, "\nAppended line."); fclose($file); echo "Appended $bytes bytes to file."; } else { echo "Failed to open file."; }
这会将新行附加到“example.txt”文件。 "\n" 创建一个新行。“a”模式会在文件不存在时创建文件,与“w”模式类似。
写入二进制数据
当文件以二进制模式打开时,fwrite
可以写入二进制数据。
binary_fwrite.php
<?php declare(strict_types=1); $file = fopen("image.png", "wb"); if ($file) { $binaryData = file_get_contents("source.png"); $bytes = fwrite($file, $binaryData); fclose($file); echo "Wrote $bytes bytes of binary data."; } else { echo "Failed to open file."; }
这通过写入二进制数据来复制 PNG 文件。模式中的“b”确保在 Windows 上正确处理二进制文件。始终对非文本文件使用二进制模式。
限制写入长度
第三个参数限制从数据字符串中写入的字节数。
limited_fwrite.php
<?php declare(strict_types=1); $file = fopen("limited.txt", "w"); if ($file) { $data = "This string is too long"; $bytes = fwrite($file, $data, 10); fclose($file); echo "Wrote $bytes bytes (limited to 10)."; } else { echo "Failed to open file."; }
仅写入前 10 个字节(“This strin”)。长度参数对于写入固定大小的块或限制输出大小很有用。
错误处理
在处理文件操作时,正确的错误处理至关重要。
error_fwrite.php
<?php declare(strict_types=1); $file = @fopen("readonly.txt", "w"); if ($file === false) { echo "Error: Could not open file."; exit; } $bytes = fwrite($file, "Test"); if ($bytes === false) { echo "Error: Write failed."; } else { echo "Successfully wrote $bytes bytes."; } fclose($file);
这展示了全面的错误处理。@ 符号抑制了 fopen 的警告。始终检查返回值是否为 false 以检测文件操作中的错误。
最佳实践
- 检查权限:确保文件是可写的。
- 错误处理:始终验证 fwrite 的返回值。
- 资源清理:完成后使用 fclose 关闭文件。
- 二进制安全:二进制数据使用“b”模式。
- 锁定:考虑使用 flock 进行并发访问。
来源
本教程通过实际示例涵盖了 PHP fwrite
函数,展示了其在不同场景下的用法。
作者
列出 所有 PHP 文件系统函数。