2-Create and modify file content
file_put_contentsWrite files
Let’s first learn the first way to write files:
int file_put_contents (string $file Path, string $write data])
Function: Write a string to the specified file. If the file does not exist, create the file. What is returned is the length of written bytes
<?php $data = "我是一個(gè)兵,來自老百姓"; $numbytes = file_put_contents('binggege.txt', $data); if($numbytes){ echo '寫入成功,我們讀取看看結(jié)果試試:'; echo file_get_contents('binggege.txt'); }else{ echo '寫入失敗或者沒有權(quán)限,注意檢查'; } ?>
We found that writing files is quite simple. According to the format of this function, specify the file and write the string data.
fwrite cooperates with fopen to perform writing operations
int fwrite (resource $file resource variable, string $written string[, int Length])
Note: The alias function of fwrite is fputs
We tried r mode in the last class, and it was only used when reading. Next, we use fwrite plus fopen. w, write mode to write files.
Let’s take a look at the features:
Open in writing mode, point the file pointer to the file header and cut the file size to zero. If the file does not exist then attempts to create it.
Note: In the following experiment, you can try to create a new test.txt file and write content into it. Then, you can try to delete test.txt. See what tips there are.
<?php $filename = 'test.txt'; $fp= fopen($filename, "w"); $len = fwrite($fp, '我是一只來自南方的狼,一直在尋找心中的花姑娘'); fclose($fp); print $len .'字節(jié)被寫入了\n"; ?>
Summary:
1. Regardless of whether there is a new file, the file will be opened and rewritten
2. The original file content will be overwritten
3. If the file does not exist, it will be created
Let’s compare the differences between the following modes:
<?php $filename = 'test.txt'; $fp= fopen($filename, "r+"); $len = fwrite($fp, '我是一只來自南方的狼,一直在尋找心中的花姑娘'); fclose($fp); print $len .'字節(jié)被寫入了\n'; ?>You can remove the + sign after r during the experiment. Through experiments, we have indeed found that using r mode, data can be written when the file is saved. If only r is used, the writing is unsuccessful. The difference between a mode and w modeThe same code is below, we change it to a mode.
<?php $filename = 'test.txt'; $fp= fopen($filename, "a"); $len = fwrite($fp,'讀大學(xué)迷茫了,PHP學(xué)院PHP給你希望'); echo $len .'字節(jié)被寫入了\n'; ?>Open the web page and execute this code, you will find: every time you refresh, there will be an extra section in the file
: If you are confused in college, PHP gives you hope.
<?php $filename = 'test.txt'; $fp= fopen($filename, "x"); $len = fwrite($fp,'讀大學(xué)迷茫了,PHP學(xué)院PHP給你希望'); echo $len .'字節(jié)被寫入了\n'; ?>We will find: 1 . When the file exists, an error will be reported 2. If you change $filename to another file name, it will be fine. However, when refreshing again, an error was reported 3. x+ is an enhanced x mode. Can also be used when reading.