PHP 檔案編程(二)

來源:互聯網
上載者:User

1、讀取檔案操作

<?php    //讀取檔案    $file_path="text.txt";    if(!file_exists($file_path)){        echo "檔案不存在";        exit();    }        //開啟檔案    $fp=fopen($file_path,"a+");    //讀取檔案    $content=fread($fp,filesize($file_path));    echo "檔案內容是:<br/>";    //預設情況下把內容輸出到網頁後,不會換行顯示,因為網頁不識別\r\n    //所有要把\r\n =><br/>        $content=str_replace("\r\n","<br/>",$content);    echo  $content;    fclose($fp);?>

2、第二種讀取檔案的方式

<?php    //第二種讀取檔案的方式    $file_path="text.txt";    if(!file_exists($file_path)){        echo "檔案不存在";        exit();    }    $content=file_get_contents($file_path);    $content=str_replace("\r\n","<br/>",$content);    echo  $content;?>

3、第三種讀取方法,迴圈讀取(對付大檔案)

<?php    //第三種讀取方法,迴圈讀取(對付大檔案)    $file_path="text.txt";    if(!file_exists($file_path)){        echo "檔案不存在";        exit();    }    //開啟檔案    $fp=fopen($file_path,"a+");    //定義每次讀取的多少位元組    $buffer=1024;    //一邊讀取。一邊判斷是否達到檔案末尾    while(!feof($fp)){        //按1024個位元組讀取資料        $content=fread($fp,$buffer);        echo $content;    }    fclose($fp);?>

 4、檔案讀取實際應用:當我們串連資料庫的時候,可以把指定的資料配置到一個檔案中,然後再PHP運行時,即時擷取資訊

db.ini 檔案

host=127.0.0.1user=rootpwd=rootdb=test

擷取檔案

<?php    $arr=parse_ini_file("db.ini");    echo "<pre>";    print_r($arr);    echo "</pre>";        echo $arr['host'];    //串連資料庫    $conn = mysql_connect($arr['host'], $arr['user'], $arr['pwd']);    if(!$conn){        echo "error";    }    echo "OK";?>

 

 

聯繫我們

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