What is the function of the fwrite function in PHP?

In PHP, the function fwrite() is used to write data to a file. More specifically, fwrite() takes three parameters: the file handle (usually obtained by using the fopen() function to open the file), the data to be written, and an optional maximum number of bytes to write.

Here is a simple example demonstrating the use of the fwrite() function.

<?php
// 打开一个文件进行写入
$myfile = fopen("example.txt", "w") or die("Unable to open file!");

// 要写入文件的内容
$txt = "Hello, world!";

// 写入数据到文件中
fwrite($myfile, $txt);

// 关闭文件
fclose($myfile);

echo "Data was written to the file successfully!";
?>

In the example above, we start by using the fopen() function to open a file named example.txt for writing, then we use the fwrite() function to write the text string “Hello, world!” to that file. Finally, we close the file handle and output a message indicating that the data was successfully written.

In summary, the function fwrite() is used to write data to an already opened file, allowing for updating, appending, and other operations on the file content.

bannerAds