To read a file in php, we need to use file_get_contents or fopen to open the file and then read it. The file_get_contents function is easier to read the file than fopen, to write a file, you must cooperate with the fopen function and file_put_contents or fwrite function. I will introduce the example below. To read a file in php, we need to use file_get_contents or fopen to open the file and then read it. The file_get_contents function is easier to read the file than fopen, to write a file, you must cooperate with the fopen function and file_put_contents or fwrite function. I will introduce the example below.
Script ec (2); script
Php file Writing Method
Instance 1
| The Code is as follows: |
|
$ Filename = 'test.txt ';
$ Filename = dirname (_ FILE _). '/'. $ filename;
If (file_exists ($ filename )){
If (! Is_writable ($ filename )){
Exit ('is not writable ');
}
$ Handle = fopen ($ filename, "a + B ");
$ Content = 'this is test word ';
$ Content. = "n ";
Fwrite ($ handle, $ content );
Fclose ($ handle );
} Else {
Exit ('file is not exists ');
} |
Instance 2
| The Code is as follows: |
|
|
$ Filename = 'test.txt ';
$ Filename = dirname (_ FILE _). '/'. $ filename;
If (file_exists ($ filename )){
If (! Is_writable ($ filename )){
Exit ('is not writable ');
}
$ Content = 'this is test word ';
$ Content. = "n ";
File_put_contents ($ filename, utf8_encode ($ content ));
} Else {
Exit ('file is not exists ');
} |
Php reads files
Instance 1
| The Code is as follows: |
|
|
$ Filename = 'test.txt ';
$ Filename = dirname (_ FILE _). '/'. $ filename;
If (file_exists ($ filename )){
If (! Is_readable ($ filename )){
Exit ('is not readable ');
}
$ Contents = file_get_contents ($ filename );
$ Contents = explode ("n", $ contents );
Print_r ($ contents );
} Else {
Exit ('file is not exists ');
} |
Instance 2
| The Code is as follows: |
|
|
$ Filename = 'test.txt ';
$ Filename = dirname (_ FILE _). '/'. $ filename;
If (file_exists ($ filename )){
If (! Is_readable ($ filename )){
Exit ('is not readable ');
}
$ Handle = fopen ($ filename, "rb ");
$ Contents = fread ($ handle, filesize ($ filename ));
// $ Contents = stream_get_contents ($ handle); // You can also use the method to replace the previous row.
$ Contents = explode ("n", $ contents );
Fclose ($ handle );
Print_r ($ contents );
} Else {
Exit ('file is not exists ');
} |