首页 > 代码库 > 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=http://www.mamicode.com/"查询"  />>

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 =http://www.mamicode.com/= $word) {>

XML 做小型数据库