Home >Backend Development >PHP Tutorial >Introduction to PHP functions—fputs(): writing content to a file
PHP function introduction—fputs(): writing content to a file
In PHP, the fputs() function is used to write content to a file. Its syntax is as follows:
fputs ( resource $handle , string $string [, int $length ] ) : int|bool
Parameter description:
handle
: File resource handle, usually obtained using the fopen()
function. string
: The string to be written. length
: Optional parameter, specifies the maximum number of bytes to be written, the default is the string length. Return value:
The number of bytes written is returned if the writing is successful, otherwise false
is returned.
Code example:
<?php $file = fopen("demo.txt", "w"); if ($file) { $content = "Hello, World!"; $length = fputs($file, $content); if ($length !== false) { echo "写入成功,共写入".$length."个字节。"; } else { echo "写入失败。"; } fclose($file); } ?>
In the above example, we open a text file named demo.txt
and write the string ## to it #Hello, World!. If the write is successful, the number of bytes written will be returned, otherwise
false will be returned.
fput() function to write to a file, the file must be opened in a writable manner. So we used the
fopen() function to open the text file in write mode. In addition, after the writing is completed, we close the file handle through the
fclose() function and release the resources.
The fputs() function is a function in PHP used to write content to a file. This function can easily write strings to the file. When using it, you need to pay attention to the opening mode of the file and the closing of the file to ensure the correctness of the operation.
The above is the detailed content of Introduction to PHP functions—fputs(): writing content to a file. For more information, please follow other related articles on the PHP Chinese website!