Share the following five methods for php to Read File Content: Well, after writing, I found that all the files are not closed. In actual application, please pay attention to the five methods of disabling fclose ($ fp) php to Read File Content
Share the following five methods for php to Read File Content: Well, after writing, I found that all the files are not closed. In actual application, close fclose ($ fp );
--
Php reads the file content:
----- Method 1 ----- fread ()--------
<? Php $ file_path = "test.txt"; if (file_exists ($ file_path) {$ fp = fopen ($ file_path, "r"); $ str = fread ($ fp, filesize ($ file_path); // specify the read size. Here, the entire file is read. echo $ str = str_replace ("\ r \ n ","
", $ Str) ;}?>
-------- Method 2 ------------
<? Php $ file_path = "test.txt"; if (file_exists ($ file_path) {$ str = file_get_contents ($ file_path ); // read the entire file content into a string $ str = str_replace ("\ r \ n ","
", $ Str); echo $ str ;}?>
----- Method 3 ------------
<? Php $ file_path = "test.txt"; if (file_exists ($ file_path) {$ fp = fopen ($ file_path, "r"); $ str = ""; $ buffer = 1024; // read 1024 bytes each time while (! Feof ($ fp) {// cyclically read until the entire file is read $ str. = fread ($ fp, $ buffer);} $ str = str_replace ("\ r \ n ","
", $ Str); echo $ str ;}?>
------- Method 4 --------------
<? Php $ file_path = "test.txt"; if (file_exists ($ file_path) {$ file_arr = file ($ file_path); for ($ I = 0; $ I
";}/* Foreach ($ file_arr as $ value) {echo $ value ."
";} */}?>
---- Method 5 --------------------
<? Php $ file_path = "test.txt"; if (file_exists ($ file_path) {$ fp = fopen ($ file_path, "r"); $ str = ""; while (! Feof ($ fp) {$ str. = fgets ($ fp); // read data row by row. If fgets does not write the length parameter, the default value is 1 k .} $ Str = str_replace ("\ r \ n ","
", $ Str); echo $ str ;}?>
The above content is shared with you five ways PHP can read file content.