XML 做小型数据库

前端之家收集整理的这篇文章主要介绍了XML 做小型数据库前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

XML可以做配置文件,也可以当数据库,这次来个数据库使用吧

1 将数据库导入到xml文件

<?PHP
/***
dict 表
id  word    mean
1   score   分数
2   title   标题
...
...
...
13121   zlib zlib库


<?xml ..?>
<dict>
<word id="w1">
    <name>score</name>
    <mean>分数</mean>
</word>
<word id="w2">
    <name>score</name>
    <mean>分数</mean>
</word>
...
....
<word id="w13211">
    <name>score</name>
    <mean>分数</mean>
</word>
</dict>


利用XML做小型数据库,做一个在线词典查询

1:把数据库的单词导入到XML文件
2:做一个表单用来发送待查询单词
3:做一个查询页面,解析XML,查询该单词
***/



$xml = new DOMDocument('1.0','utf-8');
$xml->load('./dict.xml');

$dict = $xml->getElementsByTagName('dict')->item(0);

$conn = MysqL_connect('localhost','root','111111');
MysqL_query('use test',$conn);

$rs = MysqL_query('select * from cetsix');



while($row = MysqL_fetch_assoc($rs)) {
    // 每一行数据,只要写入到XML的节点中,就可以了.

    $lx = $xml->createElement('lx');
    $lx->appendChild($xml->createCDATASection($row['lx']));

    $mean = $xml->createElement('mean');
    $mean->appendChild($xml->createCDATASection($row['meaning']));

    $name = $xml->createElement('name');
    $name->appendChild($xml->createtextNode($row['word']));

    $word = $xml->createElement('word');
    $word->appendChild($name);
    $word->appendChild($mean);
    $word->appendChild($lx);

    $dict->appendChild($word);
    
}

$xml->save('./dict.xml');

echo 'OK';


进行查询

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN">
<head>
<title>新建网页</title>
<Meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

</head>
    <body>
        <h2>XML做小型数据库,完成在线词典</h2>
        <form action="query.PHP">
            <p>
                单词:<input type="text" name="word"  />
            <p>
            <p>
                <input type="submit" value="查询"  />
            </p>
        </form>

        <div id="abc">
            分析html,干吗非得用正则,DOM解析不行吗?
        </div>

        <div><p><span>aaaa</span><span>bbbbspan</span></p></div>
    </body>
</html>

PHP代码

<?PHP
// 接收单词并解析XML查询相应的单词
$word = isset($_GET['word'])?trim($_GET['word']):'';

if(empty($word)) {
    exit('你想查啥?');
}


// 解析XML并查询
$xml = new DOMDocument('1.0','utf-8');
$xml->load('./dict.xml');


$namelist = $xml->getElementsByTagName('name');

$isfind = false;

foreach($namelist as $v) {
    if($v->nodeValue == $word) {
        //print_r($v);
        echo $word,'<br />';
        echo '意思:',$v->nextSibling->nodeValue,'<br />';
        echo '例句:',$v->nextSibling->nextSibling->nodeValue,'<br />';

        $isfind = true;
        break;
    }
}

if(!$isfind) {
    echo 'sorry';
}

猜你在找的XML相关文章