This paper introduces how PHP reads the contents of a file, summarize PHP Five ways to read the contents of a file. In practical application, please pay attention to closing fclose ($FP);
First method: 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, where the entire contents of the file are read echo $str = Str_replace ("\ r \ n", "<br/>", $str);}? >
The second method:
<?php$file_path = "Test.txt", if (file_exists ($file _path)) {$str = file_get_contents ($file _path);// Reads the entire file contents into a string $str = Str_replace ("\ r \ n", "<br/>", $str); echo $str;}? >
The third method:
<?php$file_path = "Test.txt", if (file_exists ($file _path)) {$fp = fopen ($file _path, "R"); $str = ""; $buffer = 1024;//reads 1024 bytes at a time (!feof ($fp)) {//loops through the entire file $str. = Fread ($fp, $buffer);} $str = Str_replace ("\ r \ n", "<br/>", $str); echo $str;}? >
The fourth method:
<?php$file_path = "Test.txt", if (file_exists ($file _path)) {$file _arr = file ($file _path); for ($i =0; $i <count ($ File_arr) ($i + +) {//line read the contents of the file echo $file _arr[$i]. " <br/> "; }/* foreach ($file _arr as $value) { echo $value. <br/> "; }*/}?>
The Fifth method:
<?php$file_path = "Test.txt", if (file_exists ($file _path)) {$fp = fopen ($file _path, "R"); $str = ""; while (!feof ($fp)) { $str. = Fgets ($fp);//read by line. If Fgets does not write the length parameter, the default is to read 1k. } $STR = Str_replace ("\ r \ n", "<br/>", $str); echo $str;}? >