這裡只介紹比較常用的讀取檔案的常用方法:
1,file_get_contents,將一個檔案內容讀取到一個字串中
// 讀取整個檔案if(file_exists($filepath)){ // 例如:讀取TXT檔案 $str = file_get_contents($filepath); // 編碼轉換 $str = iconv("gb2312","UTF-8",$str);}$filepath: 檔案路徑
file_exists: 判斷檔案是否存在
iconv: 轉換字元編碼
當然 file_get_contents 也可以接受讀取一個 url ,擷取 url 中的檔案內容.
2,fopen,基於此函數的相關讀取方式
2.1,常用的逐行讀取檔案
if(file_exists($filepath)){ if ($file_handle = fopen($filepath, "r")) { // 唯讀方式 // 逐行讀取 while (!feof($file_handle)) { $str .= fgetss($file_handle).'<br />'; } fclose($file_handle); } $str = iconv("gb2312","UTF-8",$str);}fopen: 開啟檔案或者url
feof(): 檢測檔案是否已經到達末尾
fgetss: 從開啟的檔案中讀取一行並過濾掉 html,php 標記(與fgets相同除了過濾標記)
fclose: 關閉檔案流
2.2,利用fread
fread 適合從二進位檔案中讀取資訊,必須指定需要讀入的位元組數.
$fh = fopen("filepath", "rb");$res= fread($file_handle, 1024);
這段代碼將讀取1024 位元組 (1kb) 的資料(fread 不會讀取超過 8192個位元組,8kb的資料)。
檔案過大隻能採取迴圈讀取,可以根據 filesize 這一函數進行判斷,if(filesize("filepath") > 8192){...}