PHP 網頁程式設計課程目錄

使用 PHP 程式搜尋文字檔案內的記錄

當使用 PHP 程式開啟及閱讀外部文字檔案後, 最主要的目的可能是搜尋某些記錄。這章課程討論如何搜尋文字檔案內的記錄。

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

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

<?php

// Record going to be searched in text file
$searchRecord = "Keung";

// 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);

// A white space will append to all records (except last record)
// This is due to the carriage return.
// Never mind! Use rtrim function to remove the white space at the end.
$value = rtrim($value);

// If the record is searched, print it out.
if ($value == $searchRecord) {
print "The value of this line is " . $value;
}
}

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

?>


</body>
</html>

PHP 語言解釋如下:

第 四 行: $searchRecord = "Keung";

這是要搜尋的記錄.

第二步: 文字檔案內容

Kong
Wai
Keung
Yau

我們仍然使用上一章的文字檔案.

第三步: 測試檔案

測試 php-read-file-search-record.php 是否可以正常執行.

瀏 灠 器 應 出 現 :

The value of this line is Keung


PHP 實例:

View PHP Example