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";?>