PHP教程之檔案讀取教程

來源:互聯網
上載者:User

這裡只介紹比較常用的讀取檔案的常用方法:

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){...}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.