標籤:pen value 關閉 檔案 exist size path 四種 contents
php讀取檔案內容的五種方式
分享下php讀取檔案內容的五種方法:好吧,寫完後發現檔案全部沒有關閉。實際應用當中,請注意關閉 fclose($fp);
php讀取檔案內容:
-----第一種方法-----fread()--------
1 <?php2 $file_path = "test.txt";3 if(file_exists($file_path)){4 $fp = fopen($file_path,"r");5 $str = fread($fp,filesize($file_path));//指定讀取大小,這裡把整個檔案內容讀取出來6 echo $str = str_replace("\r\n","<br />",$str);7 }
--------第二種方法------------
1 <?php2 $file_path = "test.txt";3 if(file_exists($file_path)){4 $str = file_get_contents($file_path);//將整個檔案內容讀入到一個字串中5 $str = str_replace("\r\n","<br />",$str);6 echo $str;7 }8 ?>
-----第三種方法------------
1 <?php 2 $file_path = "test.txt"; 3 if(file_exists($file_path)){ 4 $fp = fopen($file_path,"r"); 5 $str = ""; 6 $buffer = 1024;//每次讀取 1024 位元組 7 while(!feof($fp)){//迴圈讀取,直至讀取完整個檔案 8 $str .= fread($fp,$buffer); 9 } 10 $str = str_replace("\r\n","<br />",$str);11 echo $str;12 }13 ?>
-------第四種方法--------------
1 <?php 2 $file_path = "test.txt"; 3 if(file_exists($file_path)){ 4 $file_arr = file($file_path); 5 for($i=0;$i<count($file_arr);$i++){//逐行讀取檔案內容 6 echo $file_arr[$i]."<br />"; 7 } 8 /* 9 foreach($file_arr as $value){10 echo $value."<br />";11 }*/12 }13 ?>
----第五種方法--------------------
1 <?php 2 $file_path = "test.txt"; 3 if(file_exists($file_path)){ 4 $fp = fopen($file_path,"r"); 5 $str =""; 6 while(!feof($fp)){ 7 $str .= fgets($fp);//逐行讀取。如果fgets不寫length參數,預設是讀取1k。 8 } 9 $str = str_replace("\r\n","<br />",$str);10 echo $str;11 }12 ?>
PHP讀取檔案內容的五種方式(轉載)