爲了能夠讓不同平臺的異構數據庫之間能夠互相交換數據,完成一個數據庫的數據遷移到另一個數據庫中,可以採用XML文檔作爲數據交換的信息載體,把一個數據庫的數據轉換爲XML文檔,將XML文檔通過網絡傳輸到另一個系統,再由另一個系統平臺程序將XML文檔導入數據庫。
用DOM和SAX解析器將數據庫中的數據導出來生成XML,步驟基本爲下:
1. 建立與數據庫的連接。
2. 執行SQL語句從數據庫中檢索到數據。
3. 將檢索到的數據轉換爲XML文檔。
4. 若有必要還可將XML文檔轉化爲HTML文檔。
例如:
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Select user info from DB</title>
</head>
<body>
<?php
include "DBconnection.php";//負責連接數據庫的文件
$sql="select * from user_info";
$result=mysqli_query($conn,$sql);
if(mysqli_num_rows($result)){
$dom=new DOMDocument('1.0',"utf-8");
$dom->formatOutput=true;
$root=$dom->createElement("userinfo");
$dom->appendChild($root);
while(list($uname,$upassword,$idnumber,$phonenumber)=mysqli_fetch_array($result)){
$user=$dom->createElement("user");
$user->setAttribute('IDnumber',$idnumber);
$user->appendChild($dom->createElement("uname",$uname));
$user->appendChild($dom->createElement("upassword",$upassword));
$user->appendChild($dom->createElement("phonenumber",$phonenumber));
$root->appendChild($user);
}
$xml=$dom->saveXML();
$dom->save("userinfo.xml");
//echo $xml;
}
mysqli_close($conn);
//以下數據保存開始標籤的HTML標記
$startTags=array(
//標籤名需要大寫!
'USERINFO'=>'<table border="1" cellspacing="0" cellpadding="5">',
'USER'=>'<tr>',
'IDNUMBER'=>'<td bgcolor="silver">',
'UNAME'=>'<td bgcolor="silver">',
'UPASSWORD'=>'<td bgcolor="silver">',
'PHONENUMBER'=>'<td bgcolor="silver">',
);
$endTags=array(
'USERINFO'=>'</table>',
'USER'=>'</tr>',
'IDNUMBER'=>'</td>',
'UNAME'=>'</td>',
'UPASSWORD'=>'</td>',
'PHONENUMBER'=>'</td>',
);
//以下函數爲各個標籤的回調函數
function startElementHandler($parser,$root,$attribute){
global $startTags;
if($startTags [$root]){
//查找本開始元素對應的數組元素
echo $startTags [$root];
}
}
function endElementHandler($parser,$root){
global $endTags;
if($endTags [$root]){
echo $endTags [$root];
}
}
function characterDataHandler($parser,$data){
echo utf8_decode($data);
}
$xml=utf8_encode($xml);
$xml_parser=xml_parser_create("utf-8");
xml_set_element_handler($xml_parser,"startElementHandler","endElementHandler");
xml_set_character_data_handler($xml_parser,"characterDataHandler");
if(!xml_parse($xml_parser,$xml)){
$error_code=xml_get_error_code($xml_parser);
die("XML解析錯誤(錯誤代碼".$error_code."):".xml_error_string($error_code)."<br>錯誤發生的行"
.xml_get_current_line_number($xml_parser) ."錯誤發生的列".xml_get_current_column_number($xml_parser)
."錯誤發生的字節".xml_get_current_byte_index($xml_parser));
}
xml_parser_free($xml_parser);
?>
</body>
</html>
運行後的效果大致如下:(即以表格的形式從數據庫中讀出數據並將相應的標記轉化爲HTML標記)
在上述程序中,我查詢的user_info表的具體創建如下,可以蠻參考一下:
CREATE TABLE user_info (
uname VARCHAR(20) NOT NULL KEY,
upassword VARCHAR(20) NOT NULL,
idnumber VARCHAR(20) NOT NULL,
phonenumber VARCHAR(20) NOT NULL
)