fputs()
将字符串写入打开的文件中
函数名:fputs()
适用版本:PHP 4, PHP 5, PHP 7
函数描述:fputs() 函数用于将字符串写入打开的文件中。
用法:
fputs ( resource $handle , string $string [, int $length ] ) : int
参数:
$handle:必需,文件资源类型的句柄,通过 fopen() 函数打开文件获得。
$string:必需,要写入文件的字符串。
$length:可选,指定要写入的最大长度,默认为字符串的长度。
返回值:
成功时返回写入的字节数,失败时返回 false。
示例:
<?php
$filename = "example.txt";
$handle = fopen($filename, "w");
if ($handle) {
$content = "Hello, World!";
$bytes_written = fputs($handle, $content);
if ($bytes_written === false) {
echo "写入文件失败";
} else {
echo "成功写入 $bytes_written 字节";
}
fclose($handle);
} else {
echo "无法打开文件";
}
?>
在上述示例中,我们首先使用 fopen() 函数打开一个文件,然后使用 fputs() 函数将字符串 "Hello, World!" 写入文件。最后,使用 fclose() 函数关闭文件句柄。如果写入成功,将输出成功写入的字节数;如果写入失败,将输出错误信息。