標籤:
PHP中XPATH 實現xml及html檔案快速解析(附xml做小型資料庫實現六級單詞快速查詢執行個體)
一、XPATH簡單入門
XPATH ,XQUERY 專門查詢XML語言,查詢速度快
使用方法:
(1)建立DOM工具,並且載入 xml檔案
$xml = new DOMDocument(‘1.0‘,‘utf-8‘);
$xml -> load(‘./dict.xml‘);
註:若是對html檔案進行快速解析, 同樣的道理
此處使用 loadhtmlfile (‘dict.html’);
(2)建立xpath解析工具
$xpath = new DOMXPATH($xml);
(3)編寫xpath查詢語句
$sql = ‘/dict/word[name="‘.$word.‘"]/name‘;
註:若是對html檔案進行快速解析
$sql = ‘/html/body/div/h2’; //得到body下的div下面的h2標籤下的內容
(4)查詢語句,返回結果
$words = $xpath->query($sql);
下面是查詢語句表的一些文法
二、xml做小型資料庫實現六級單詞快速查詢執行個體
初步版本:缺點:查詢速度慢
//接收單詞並解析XML查詢相應的單詞
$word = isset($_GET[‘word‘])?trim($_GET[‘word‘]):‘‘;
if(empty($word)){
exit("I am sorry,I can‘t catch the word!");
}else{
$xml = new DOMDocument(‘1.0‘,‘utf-8‘);
$xml -> load(‘./dict.xml‘);
// * DOM實現解析並查詢
$namelist = $xml->getElementsByTagName(‘name‘);
$value = array();
$isfind = false;
foreach($namelist as $v){
if(($v->nodeValue) == $word){
//print_r($v);
echo $word,"<br/>";
echo "Meaning:",$v->nextSibling->nodeValue,"<br/>";
echo "Example:",$v->nextSibling->nextSibling->nodeValue,"<br/>";
//$value[‘Word‘] = $word;
//$value[‘Meaning‘] = $v->nextSibling->nodeValue;
//$value[‘Example‘] = str_replace(‘/r/n‘,"<br/>",$v->nextSibling->nextSibling->nodeValue);
$isfind = true;
break;
}
}
if(!$isfind)
echo "<br/><h3>Sorry,the word is not in the directory</h3>";
使用XPATH改進版本:速度快
使用執行個體:
$word = isset($_GET[‘word‘])?trim($_GET[‘word‘]):‘‘;
if(empty($word)){
exit("I am sorry,I can‘t catch the word!");
}else{
$xml = new DOMDocument(‘1.0‘,‘utf-8‘);
$xml -> load(‘./dict.xml‘);
$xpath = new DOMXPATH($xml);
//查詢dict下面的word,並且name=$word的節點 下的//name節點
$sql = ‘/dict/word[name="‘.$word.‘"]/name‘;
$words = $xpath->query($sql);
if($words->length == 0){ //如果沒有這個單詞
echo "<br/><h3>Sorry,the word is not in the directory</h3>";
exit;
}
//走到這一步,說明查到了
Echo "<b>Word:</b>"," ","<B>$word
</B>","<br/>";
echo "<b>Meaning:</b>",$name->nextSibling->nodeValue,"<br/>";
echo "<b>Example:</b>",$name->nextSibling->nextSibling->nodeValue,"<br/>";
//$value[‘Word‘] = $word;
//$value[‘Meaning‘] = $name->nextSibling->nodeValue;
//$value[‘Example‘] = str_replace(‘/r/n‘,"<br/>",$name->nextSibling->nextSibling->nodeValue);
}
附上HTML檔案代碼:
<html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>dict</title> </head> <style> //style="text-align:center;"} </style> <body> <div > <h2>XML做小型資料庫實現線上詞典</h2> <!-- <form action="dict.php"> --> <form> <p>單詞:<input type=‘text‘ name=‘word‘/></p> <p><input type="submit" value="查詢"/></p> </form> <p> <?PHP if(isset($value[‘Word‘])) { foreach($value as $k=>$v){ ?> <b ><?php echo $k.": ";?></b> <p ><?php echo $v;?></p> <br/> <?php } }?> </p> </div> </body></html>
結果如果所示:
三、使用XPATH快速查詢html檔案執行個體
$html = new DOMDocument(‘1.0‘,‘utf-8‘);
$html -> loadhtmlfile(‘./dict.html‘);
$xpath= new DOMXPATH($html);
$sql = ‘/html/body/div/h2’; //得到body下的div下面的h2標籤下的內容
Echo $xpath->query($sql)->item(0)->nodeValue;
PHP中XPATH 實現xml及html檔案快速解析(附xml做小型資料庫實現六級單詞快速查詢執行個體)