-----The 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, here read the entire file content echo $str = str_replace( " \r\n " , " <br /> " , $str); fclose($fp); } ?>
--------The second method------------
<?php $file_path = "test.txt"; if(file_exists($file_path)){ $str = file_get_contents($file_path); // Read the entire file contents into a string $str = str_replace( " \r\n " , " <br /> " ,$str); echo $str; } ?>
-----Third method------------
<?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)){ // Read in a loop until the entire file is read $str .= fread($fp,$buffer); } $str = str_replace("\r\n","<br />",$str); echo $str; fclose($fp); } ?>
-------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++){ // Read the file content line by line echo $file_arr[$i]. " <br /> " ; fclose($file_arr); } /* 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 line 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; fclose($fp); } ?>
All five methods must remember to close the file fclose($fp);
Reprinted to http://www.jb51.net/article/77067.htm