php+xml實現線上英文詞典之添加詞條的方法_php技巧

來源:互聯網
上載者:User

本文執行個體講述了php+xml實現線上英文詞典之添加詞條的方法。分享給大家供大家參考。具體如下:

接著上一篇《php+xml實現線上英文詞典查詢的方法》,這裡要添加一個功能,提交英文單詞和中文意思,將這些資訊添加到xml文檔中。

xml檔案(資料庫):words.xml

複製代碼 代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<words>
<word>
 <en>boy</en>
 <ch>男孩</ch>
</word>
<word>
 <en>girl</en>
 <ch>女孩</ch>
</word>
<word>
 <en>teacher</en>
 <ch>老師</ch>
</word>
<word>
 <en>beauty</en>
 <ch>美女</ch>
</word>
</words>

查詢與添加檔案:words.php

複製代碼 代碼如下:
<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>

處理檔案:xmlprocess.php

複製代碼 代碼如下:
<?php
//建立xml對象
$xmldoc = new DOMDocument();
$xmldoc->load("words.xml");
//查詢
if(!empty($_POST['sub'])){
 $en_word = $_POST['enword'];
 $word = $xmldoc->getElementsByTagName("en");
 for($i=0;$i<$word->length;$i++){
  if($en_word==$word->item($i)->nodeValue){
   $cn_word = $xmldoc->getElementsByTagName("ch")->item($i)->nodeValue;
   break;
  }else{
   $cn_word = "找不到你所輸入的單詞";
  }
 }
 echo $cn_word;
}
//增加詞條
if(!empty($_POST['add'])){
 $en_word = $_POST['en_word'];
 $ch_word = $_POST['ch_word'];
 //擷取根節點
 $words = $xmldoc->getElementsByTagName("words")->item(0);
 //增加元素,並新增內容
 $new_word = $xmldoc->createElement("word");
 $new_word_en = $xmldoc->createElement("en");
 $new_word_en->nodeValue = $en_word;
 $new_word_ch = $xmldoc->createElement("ch");
 $new_word_ch->nodeValue = $ch_word;
 //元素之間掛載,意思是將子項目與父元素相連
 $new_word->appendChild($new_word_en);
 $new_word->appendChild($new_word_ch);
 $words->appendChild($new_word);
 //儲存
 $xmldoc->save("words.xml");
}
?>

希望本文所述對大家的php+XML程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.