Modify function: 1. fwrite(), you can write a string to a file, the syntax is "fwrite(specify file, write data, number of bytes written)"; 2. file_put_contents( ), syntax "file_put_contents(file name, written data, writing mode)".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
There are two functions in php to modify files: fwrite () and file_put_contents() function
1, fwrite() function
fwrite() function can write a string to a file, the syntax format of the function As follows:
fwrite(resource $handle, string $string[, int $length])
The parameter description is as follows:
$handle: The file to be written is the resource created by fopen();
$string: The string to be written;
$length: Optional parameter, used to set the number of bytes to be written.
The fwrite() function can write the contents of $string to the file pointer $handle. If $length is specified, writing will stop when $length bytes have been written or $string has been written. If the function is successfully executed, the number of bytes written will be returned. If the function fails, FALSE will be returned.
Example: There is a text file named "test.txt", the content is:
##
<?php header("Content-Type: text/html;charset=utf-8"); //设置字符编码 $file = "test.txt"; $handle = fopen($file, 'w'); //打开文件 fwrite($handle, 'HELLO PHP!'); //写入内容 fclose($handle);//关闭文件 ?>
readfile($file); //读取并输出文件全部内容
2. file_put_contents() function
file_put_contents() function has the same function as fwrite() function. It can also write a string to a file. The syntax format As follows:file_put_contents(string $filename, mixed $data[, int $flags = 0[, resource $context]])
operator):
<?php header("Content-Type: text/html;charset=utf-8"); //设置字符编码 $file = "test.txt"; file_put_contents($file, '欢迎来到PHP中文网!'); //写入内容 readfile($file); //读取并输出文件全部内容 ?>
<?php header("Content-Type: text/html;charset=utf-8"); //设置字符编码 $file = "test.txt"; file_put_contents($file, '欢迎来到PHP中文网!33',FILE_APPEND|LOCK_EX); //写入内容 readfile($file); //读取并输出文件全部内容 ?>
PHP Video Tutorial"
The above is the detailed content of What is the function to modify files in php. For more information, please follow other related articles on the PHP Chinese website!