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 參考手冊。