function print_xml(){
//獲取數據庫連接
$link=@mysql_connect("localhost","root","") or die('數據庫連接錯誤');
//選擇數據庫
mysql_select_db("compass",$link);
//設置數據庫編碼
mysql_query("set names utf8",$link);
//查詢數據庫
$result=mysql_query("select * from product");
//創建DOMDocument對象
$doc = new DOMDocument('1.0','utf-8');
//格式化輸出
$doc->formatOutput = true;
//創建跟元素
$root = $doc->createElement('root');
//添加跟元素
$root = $doc->appendChild($root);
//從數據庫中獲取數據每一條是一個product
while($data=mysql_fetch_assoc($result)){
//創建Id元素
$id = $doc->createElement('id');
//添加Id
$id = $root->appendChild($id);
//創建文本內容
$idtext = $doc->createTextNode($data['id'].'');
//將文本添加到id標簽內
$idtext = $id->appendChild($idtext);
//創建name標簽
$name = $doc->createElement('name');
//添加name
$name = $root->appendChild($name);
//創建name標簽的文本
$nametext = $doc->createTextNode($data['name'].'');
//設置name標簽的文本
$nametext = $name->appendChild($nametext);
//創建price標簽
$price = $doc->createElement('price');
//添加price
$price = $root->appendChild($price);
//創建price標簽的文本
$pricetext = $doc->createTextNode($data['price'].'');
//設置price標簽的文本
$pricetext = $price->appendChild($pricetext);
}
//關閉數據庫連接
mysql_close($link);
//保存xml
echo $doc->saveXML();
}