File Operations in PHP (1) -- Open/read files,
1. Open a file (fopen)
Syntax: resource $ fp = fopen (file address, mode), returns a file pointer (file pointer)
Mode |
Description |
R |
Read-Only |
W |
Write (clear and overwrite) |
A |
Append |
$ Fp = fopen ('. /aa.txt ', "r"); // read-only $ fp = fopen ('. /aa.txt ', "w"); // write (clear overwrite) $ fp = fopen ('. /aa.txt ', "a"); // append
2. Read the file (Fread, file_get_contents)
Syntax: stringFread($ Fp, file size)
File_get_contents reads the entire file into a string
Syntax: stringFile_get_contents(String$ Filename)
<? Php $ filename = '. /aa.txt '; echo "<br> ****** first read method ******** <br> "; $ fp = fopen ($ filename, "r"); $ con = fread ($ fp, filesize ($ filename )); // by default, the content displayed on the webpage does not wrap. You need to replace the line break \ r \ n-> <br/> $ con = str_replace ("\ r \ n ", "<br/>", $ con); echo "$ con"; // close the pointer fclose ($ fp ); echo "<br> ****** the second method for reading data cyclically (applies to large files) ******** <br> "; $ fp = fopen ($ filename, "r"); // sets the buffer to read 1024 bytes at a time. $ buffer = 1024; // checks whether the file pointer is at the end of the file while (! Feof ($ fp) {// read $ con = fread ($ fp, $ buffer); // Replace the linefeed $ con = str_replace ("\ r \ n ", "<br/>", $ con); echo "$ con" ;}// close the pointer fclose ($ fp ); echo "<br> ******* third read method ********* <br>"; $ con = file_get_contents ($ filename ); // Replace the linefeed $ con = str_replace ("\ r \ n", "<br/>", $ con); echo "$ con ";
Result:
3. fgets (): Read a row and move the pointer down a row.
$filename = "aa.txt";$fp = fopen($filename, 'r');while (!feof($fp)) {echo fgets($fp)."<br/>";}
Result:
$ Filename = "aa.txt"; fseek ($ fp, 0); // move the file pointer to the beginning of the file while (! Feof ($ fp) {echo fgets ($ fp). "<br/> ";}
Result:
4. getc (): Get a character
$ Filename = "aa.txt"; $ fp = fopen ($ filename, 'R'); while (! Feof ($ fp) {// obtain a Chinese character, occupying 3 bytes echo fqetc ($ fp). "<br/> ";}