PHP讀取檔案內容的五種方式

來源:互聯網
上載者:User

標籤:沒有   ref   contents   art   http   syntax   content   div   key   

php讀取檔案內容的五種方式

分享下php讀取檔案內容的五種方法:好吧,寫完後發現檔案全部沒有關閉。實際應用當中,請注意關閉 fclose($fp);
--

php讀取檔案內容:

-----第一種方法-----fread()--------

?
12345678 <?php$file_path = "test.txt";if(file_exists($file_path)){$fp = fopen($file_path,"r");$str = fread($fp,filesize($file_path));//指定讀取大小,這裡把整個檔案內容讀取出來echo $str = str_replace("\r\n","<br />",$str);}?>

--------第二種方法------------

?
12345678 <?php$file_path = "test.txt";if(file_exists($file_path)){$str = file_get_contents($file_path);//將整個檔案內容讀入到一個字串中$str = str_replace("\r\n","<br />",$str);echo $str;}?>

-----第三種方法------------

?
12345678910111213 <?php$file_path = "test.txt";if(file_exists($file_path)){$fp = fopen($file_path,"r");$str = "";$buffer = 1024;//每次讀取 1024 位元組while(!feof($fp)){//迴圈讀取,直至讀取完整個檔案$str .= fread($fp,$buffer);} $str = str_replace("\r\n","<br />",$str);echo $str;}?>

-------第四種方法--------------

?
12345678910111213 <?php$file_path = "test.txt";if(file_exists($file_path)){$file_arr = file($file_path);for($i=0;$i<count($file_arr);$i++){//逐行讀取檔案內容echo $file_arr[$i]."<br />";}/*foreach($file_arr as $value){echo $value."<br />";}*/}?>

----第五種方法--------------------

?
123456789101112 <?php$file_path = "test.txt";if(file_exists($file_path)){$fp = fopen($file_path,"r");$str ="";while(!feof($fp)){$str .= fgets($fp);//逐行讀取。如果fgets不寫length參數,預設是讀取1k。}$str = str_replace("\r\n","<br />",$str);echo $str;}?>

以上內容給大家分享了PHP讀取檔案內容的五種方式,希望大家喜歡。

PHP讀取檔案內容的五種方式

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.