php讀取檔案內容的三種方法

來源:互聯網
上載者:User

標籤:substr   while   判斷   檔案   nts   use   for   替換字串   else   

<?php//**************第一種讀取方式*****************************代碼如下:header("content-type:text/html;charset=utf-8");//檔案路徑$file_path = "text.txt";//判斷是否有這個檔案if (file_exists($file_path)) {    if ($fp = fopen($file_path, "a+")) {        //讀取檔案        $conn = fread($fp, filesize($file_path));        //替換字串        $conn = str_replace("rn", "<br/>", $conn);        echo $conn . "<br/>";    } else {        echo "檔案打不開";    }} else {    echo "沒有這個檔案";}fclose($fp); //*******************第二種讀取方式***************************代碼如下:header("content-type:text/html;charset=utf-8");//檔案路徑$file_path = "text.txt";$conn      = file_get_contents($file_path);$conn      = str_replace("rn", "<br/>", file_get_contents($file_path));echo $conn;fclose($fp); //******************第三種讀取方式,迴圈讀取*****************代碼如下:header("content-type:text/html;charset=utf-8");//檔案路徑$file_path = "text.txt";//判斷檔案是否存在if (file_exists($file_path)) {    //判斷檔案是否能開啟    if ($fp = fopen($file_path, "a+")) {        $buffer = 1024;        //邊讀邊判斷是否到了檔案末尾        $str = "";        while (!feof($fp)) {            $str .= fread($fp, $buffer);        }    } else {        echo "檔案不能開啟";    }} else {    echo "沒有這個檔案";}//替換字元$str = str_replace("rn", "<br>", $str);echo $str;fclose($fp);讀取INI設定檔的函數:$arr = parse_ini_file("config.ini");//返回的是數組echo $arr[‘host‘] . "<br/>";echo $arr[‘username‘] . "<br/>";echo $arr[‘password‘] . "<br/>"; //_______________________讀取大檔案$fp   = fopen($file, "r");$num   = 10;$chunk = 4096;$fs    = sprintf("%u", filesize($file));$max   = (intval($fs) == PHP_INT_MAX) ? PHP_INT_MAX : filesize($file);for ($len = 0; $len < $max; $len += $chunk) {    $seekSize = ($max - $len > $chunk) ? $chunk : $max - $len;    fseek($fp, ($len + $seekSize) * -1, SEEK_END);    $readData = fread($fp, $seekSize) . $readData;     if (substr_count($readData, "n") >= $num + 1) {        preg_match("!(.*?n){" . ($num) . "}$!", $readData, $match);        $data = $match[0];        break;    }}fclose($fp);echo $data;

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.