PHP 網頁程式設計課程目錄

使用 PHP 程式開啟(Open File)及閱讀(Read File)外部文字檔案

編寫一些簡單程式, 很多時都需要使用外部的文字檔案 (External Text File)。其實, 這些外部文字檔案很多時都充當一個簡單的資料庫。

這章課程討論如何開啟及閱讀外部文字檔案。

第一步: 加入以下 PHP 語言於 HTML 文件中

<html>
<body>
<p>PHP Open and Read text File</p>

<?php

// Use fopen function to open a file
$file = fopen("family.txt", "r");

// Read the file line by line until the end
while (!feof($file)) {
$value = fgets($file);
print "The value of this line is " . $value . "<br>";
}

// Close the file that no longer in use
fclose($file);

?>


</body>
</html>

PHP 語言解釋如下:

第 八 行: $file = fopen("family.txt", "r");

使用 fopen 開啟 family.txt 文字檔案. 注意文字檔案的正確路徑.

第二步: 文字檔案內容

Kong
Wai
Keung
Yau

上傳文字檔案. 文字檔案和 PHP 檔案在在同一目錄下.

第三步: 測試檔案

測試 php-open-file-and-read-file.php 是否可以正常執行.

瀏 灠 器 應 出 現 :

The value of this line is Kong
The value of this line is Wai
The value of this line is Keung
The value of this line is Yau


PHP 實例:

View PHP Example