: This article mainly introduces five methods for PHP to read file content. For more information about PHP tutorials, see. Five methods for 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.
The above describes the five methods for PHP to read file content, including content, and hope to be helpful to friends who are interested in PHP tutorials.