PHP如何使用fwrite()函数写入文件?

2021年3月26日16:52:09 发表评论 719 次浏览

PHP中的fwrite()函数是一个内置函数, 用于写入打开的文件。 fwrite()函数在文件末尾或达到指定长度(作为参数传递)时停止, 以先到者为准。文件, 字符串和必须写入的长度作为参数发送到fwrite()函数, 它返回成功时写入的字节数, 失败时返回FALSE。

语法如下:

fwrite(file, string, length)

参数:PHP中的fwrite()函数接受三个参数。

  1. 文件:这是指定文件的必需参数。
  2. String:这是必填参数, 用于指定要写入的字符串。
  3. 长度:这是一个可选参数, 它指定要写入的最大字节数。

返回值:它返回成功写入的字节数, 失败返回False。

例外情况:

  1. 由于fwrite()是二进制安全的, 因此可以使用此函数来写入图像和字符数据等二进制数据。
  2. 如果对文件指针执行两次写入操作, 则数据将被附加到文件内容的末尾。

例子:

Input : $myfile = fopen("gfg.txt", "w");
        echo fwrite($myfile, "lsbin is a portal for geeks!");
        fclose($myfile);
Output : 36

Input : $myfile = fopen("gfg.txt", "w");
        echo fwrite($myfile, "PhP is Simple to Learn!");
        echo fwrite($myfile, "lsbin is a portal for geeks!");
        fclose($myfile);
Output : 23
         59

下面的程序说明了fwrite()函数:

程序1:

<?php
// Opening a file
$myfile = fopen ( "gfg.txt" , "w" );
  
// writing content to a file using fwrite()
echo fwrite( $myfile , "lsbin is a portal for geeks!" );
  
// closing the file
fclose( $myfile );
?>

输出如下:

36

程序2:

<?php
// Opening a file
$myfile = fopen ( "gfg.txt" , "w" );
  
// writing content to a file using fwrite()
echo fwrite( $myfile , "PhP is Simple to Learn!" );
echo fwrite( $myfile , "lsbin is a portal for geeks!" );
  
// closing the file
fclose( $myfile );
?>

输出如下:

23
59

参考: http://php.net/manual/en/function.fwrite.php


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: