PHP is a very common development language and one of the languages commonly used for website backend development. In the daily development process, sometimes the content of the file needs to be rewritten. So, how to use PHP to achieve it?
1. Open the file and read the content
First, we need to open the file and read the content. The file can be opened using PHP's fopen() function, and the fread() function can be used to read the file contents. The following is an example of reading the contents of a file:
$file = fopen("file.txt", "r"); $content = fread($file, filesize("file.txt")); fclose($file);
In the above code, we use the fopen() function to open the file named "file.txt" and open it in read mode. Then, use the fread() function to read the file content and assign the content to the variable $content. Finally, use the fclose() function to close the file handle.
2. Change the file content and save it
Next, we need to change the file content and save it. Use PHP's fwrite() function to write new content to the file. The following is an example of changing the file content and saving it:
$file = fopen("file.txt", "w"); $content = "hello world"; fwrite($file, $content); fclose($file);
In the above code, we use the fopen() function to open the file named "file.txt" and open it in writing mode. Then, use the fwrite() function to write the new content "hello world" to the file. Finally, use the fclose() function to close the file handle.
3. Complete example
The following is a complete PHP code example, which can read the file content and change the file content, and finally save it to the file:
$file = fopen("file.txt", "r"); $content = fread($file, filesize("file.txt")); fclose($file); $content = str_replace("old content", "new content", $content); $file = fopen("file.txt", "w"); fwrite($file, $content); fclose($file);
Above In the code, we first use the fopen() function to open the file named "file.txt" and open it in read mode. Then, use the fread() function to read the file content and assign the content to the variable $content. Next, use the str_replace() function to change the file content, replacing "old content" with "new content". Finally, use the fwrite() function to write the changed content to the file, and use the fclose() function to close the file handle.
Summary
The above is how to use PHP to rewrite the content of the file. It should be noted that the original file must be backed up before rewriting the file content to avoid data loss.
The above is the detailed content of php rewrite file content. For more information, please follow other related articles on the PHP Chinese website!