程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> php讀取文件內容的方法匯總,

php讀取文件內容的方法匯總,

編輯:關於PHP編程

php讀取文件內容的方法匯總,


本文實例匯總了php讀取文件內容的方法。分享給大家供大家參考。具體如下:

這裡匯總php讀取文件內容的五種方法。實際應用當中,請注意關閉 fclose($fp);

第一種方法:fread()
復制代碼 代碼如下:<?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);
}
?>
第二種方法:
復制代碼 代碼如下:<?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;
}
?>
第三種方法:
復制代碼 代碼如下:<?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;
}
?>
第四種方法:
復制代碼 代碼如下:<?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 />";
 }*/
}
?>
第五種方法:
復制代碼 代碼如下:<?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程序設計有所幫助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved