fopen()是用來打開文件,在PHP 。
第一個參數的這一功能包含文件的名稱將開放第二個參數指定的文件模式應打開:
<html>
<body><?php
$file=fopen("welcome.txt","r");
?></body>
</html>
The file may be opened in one of the following modes:
Modes Description
r Read only. Starts at the beginning of the file
r+ Read/Write. Starts at the beginning of the file
w Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist
w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist
a Append. Opens and writes to the end of the file or creates a new file if it doesn't exist
a+ Read/Append. Preserves file content by writing to the end of the file
x Write only. Creates a new file. Returns FALSE and an error if file already exists
x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists
注意:如果fopen()函數是無法打開指定的文件,它返回0 (假) 。
例如
下面的例子生成一個訊息,如果fopen()函數是無法打開指定的文件:
<html> <body>
<?php $file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
</body> </html>
fclose 關閉文件
該fclose ( )函數是用來關閉一個開放的檔案
<?php $file = fopen("test.txt","r");
//some code to be executed
fclose($file); ?>
檢查文件結束
該feof ( )函數檢查如果“文件結束” (的EOF )已經達成。
該feof ( )函數是有益的循環,通過數據的未知的長度。
注意:您不能讀取檔案開放瓦特,一個,和x模式
if (feof($file)) echo "End of file";讀文件一行行
該fgets ( )函數是用來讀取一個單一的從一個文件。
注意:在調用此函數的文件指針已經移到下一行。
例如
下面的例子中讀取文件一行行,直至到達文件:<?php $file = fopen("welcome.txt", "r") or exit("Unable to open file!"); //Output a line of the file until the end is reached while(!feof($file)) { echo fgets($file). "<br />"; } fclose($file); ?>讀文件的性格特征
該fgetc ( )函數是用來讀取一個字符從一個檔案。
注意:在調用此函數的文件指針移動到下一個字符。
例如
下面的例子中讀取一個文件性質的特點,到年底達成的文件是:
<?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); while (!feof($file)) { echo fgetc($file); } fclose($file); ?>