承接前篇查詢功能,本文示範如何讓使用者輸入英文單字與中文釋義,並將新詞條寫入 XML「資料庫」。涵蓋表單設計、DOM 節點建立與掛載、檔案持久化儲存等關鍵步驟。
<h2 style="color:green">線上英漢詞典</h2>
<h4>查詢英文單字</h4>
<form action="xmlprocess.php" method="post">
請輸入英文單字:<input type="text" name="enword" />
<input type="submit" value="查詢" name="sub" />
</form>
<h4>新增英文單字</h4>
<form action="xmlprocess.php" method="post">
英文單字:<input type="text" name="en_word" /><br />
中文意思:<input type="text" name="ch_word" />
<input type="submit" value="新增" name="add">
</form>
<?php
$xmldoc = new DOMDocument();
$xmldoc->load("words.xml");
// 查詢邏輯
if (!empty($_POST['sub'])) {
$en_word = $_POST['enword'];
$word_nodes = $xmldoc->getElementsByTagName("en");
$cn_word = "找不到您輸入的單字";
for ($i = 0; $i < $word_nodes->length; $i++) {
if ($en_word == $word_nodes->item($i)->nodeValue) {
$cn_word = $xmldoc->getElementsByTagName("ch")->item($i)->nodeValue;
break;
}
}
echo $cn_word;
}
// 新增詞條邏輯
if (!empty($_POST['add'])) {
$en_word = $_POST['en_word'];
$ch_word = $_POST['ch_word'];
// 取得根節點 <words>
$words = $xmldoc->getElementsByTagName("words")->item(0);
// 建立新節點結構
$new_word = $xmldoc->createElement("word");
$new_en = $xmldoc->createElement("en", $en_word);
$new_ch = $xmldoc->createElement("ch", $ch_word);
// 節點掛載:word → en, ch → words
$new_word->appendChild($new_en);
$new_word->appendChild($new_ch);
$words->appendChild($new_word);
// 持久化儲存
$xmldoc->save("words.xml");
echo "詞條新增成功!";
}
?>
DOMXPath 替代 getElementsByTagName,查詢更彈性。此範例展示 PHP 操作 XML 完成 CRUD 中「Create」與「Read」的核心流程,是理解伺服端資料持久化的優良入門教材。