PHP 檔處理
fopen() 函數用於在 PHP 中打開檔。
打開檔
fopen() 函數用於在 PHP 中打開檔。
此函數的第一個參數含有要打開的檔的名稱,第二個參數規定了使用哪種模式來打開檔:
<html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>
檔可能通過下列模式來打開:
模式 | 描述 |
---|---|
r | 只讀。在檔的開頭開始。 |
r+ | 讀/寫。在檔的開頭開始。 |
w | 只寫。打開並清空文件的內容;如果檔不存在,則創建新檔。 |
w+ | 讀/寫。打開並清空文件的內容;如果檔不存在,則創建新檔。 |
a | 追加。打開並向檔末尾進行寫操作,如果檔不存在,則創建新檔。 |
a+ | 讀/追加。通過向檔末尾寫內容,來保持檔內容。 |
x | 只寫。創建新檔。如果檔已存在,則返回 FALSE 和一個錯誤。 |
x+ | 讀/寫。創建新檔。如果檔已存在,則返回 FALSE 和一個錯誤。 |
注釋:如果 fopen() 函數無法打開指定檔,則返回 0 (false)。
實例
如果 fopen() 函數不能打開指定的檔,下麵的實例會生成一段消息:
<html>
<body>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
</body>
</html>
<body>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
</body>
</html>
關閉檔
fclose() 函數用於關閉打開的檔:
<?php
$file = fopen("test.txt","r");
//執行一些代碼
fclose($file);
?>
$file = fopen("test.txt","r");
//執行一些代碼
fclose($file);
?>
檢測檔末尾(EOF)
feof() 函數檢測是否已到達檔末尾(EOF)。
在迴圈遍曆未知長度的數據時,feof() 函數很有用。
注釋:在 w 、a 和 x 模式下,您無法讀取打開的檔!
if (feof($file)) echo "檔結尾";
逐行讀取檔
fgets() 函數用於從檔中逐行讀取檔。
注釋:在調用該函數之後,檔指針會移動到下一行。
實例
下麵的實例逐行讀取檔,直到檔末尾為止:
<?php
$file = fopen("welcome.txt", "r") or exit("無法打開檔!");
// 讀取檔每一行,直到檔結尾
while(!feof($file))
{
echo fgets($file). "<br>";
}
fclose($file);
?>
$file = fopen("welcome.txt", "r") or exit("無法打開檔!");
// 讀取檔每一行,直到檔結尾
while(!feof($file))
{
echo fgets($file). "<br>";
}
fclose($file);
?>
逐字元讀取檔
fgetc() 函數用於從檔中逐字元地讀取檔。
注釋:在調用該函數之後,檔指針會移動到下一個字元。
實例
下麵的實例逐字元地讀取檔,直到檔末尾為止:
<?php
$file=fopen("welcome.txt","r") or exit("無法打開檔!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>
$file=fopen("welcome.txt","r") or exit("無法打開檔!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>
PHP Filesystem 參考手冊
如需查看 PHP 檔系統函數的完整參考手冊,請訪問我們的PHP Filesystem 參考手冊。