本文實(shí)例講述了PHP創(chuàng)建XML接口的方法。分享給大家供大家參考,具體如下:
xml接口:即一個(gè)供用戶(hù)請(qǐng)求的頁(yè)面地址,該地址返回一個(gè)xml文檔信息。
下面的例子利用xml獲取最新的10條商品信息
?php
header("content-type:text/html;charset=utf-8");
//制作xml接口,提供網(wǎng)站最新的10條商品信息
$link = mysql_connect('localhost','root','123');
mysql_select_db('shop',$link);
mysql_query('set names utf8');
/*
shop>
goods>
name>/name>
price>/price>
number>/number>
/goods>
......
/shop>
*/
$sql = "select goods_name, goos_price, goods_number from sw_goods order by goods_id desc limit 10";
$qry = mysql_query($sql);//接收的是一個(gè)結(jié)果集
$info = array();
//取出每一條記錄
while($re = mysql_fetch_assoc($qry)){
//$re 是一維數(shù)組,代表每條記錄
$info[] = $re;//$info是二維數(shù)組,接收每條記錄
}
$dom = new DOMDocument('1.0', 'utf-8');
$shop = $dom -> createElement('shop');//創(chuàng)建根節(jié)點(diǎn)
for($i=0; $icount($info); $i++){
//創(chuàng)建元素節(jié)點(diǎn)
$goods = $dom -> createElement('goods');
$name = $dom -> createElement('name');
$price = $dom -> createElement('price');
$number = $dom -> createElement('number');
//創(chuàng)建文本節(jié)點(diǎn)
$name_txt = $dom -> createTextNode($info[$i]['goods_name']);
$price_txt = $dom -> createTextNode($info[$i]['goods_price']);
$number_txt = $dom -> createTextNode($info[$i]['goods_number']);
//追加節(jié)點(diǎn)
$name -> appendChild($name_txt);
$price -> appendChild($price_txt);
$number -> appendChild($number_txt);
$goods -> appendChild($name);
$goods -> appendChild($price);
$goods -> appendChild($number);
$shop -> appendChild($goods);
}
$dom -> appendChild($shop);//追加根節(jié)點(diǎn)
header("content-type:text/xml;charset=utf-8");
echo $dom -> saveXML();
PS:這里再為大家提供幾款關(guān)于xml操作的在線工具供大家參考使用:
在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson
在線格式化XML/在線壓縮XML:
http://tools.jb51.net/code/xmlformat
XML在線壓縮/格式化工具:
http://tools.jb51.net/code/xml_format_compress
XML代碼在線格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《PHP針對(duì)XML文件操作技巧總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《php+mysql數(shù)據(jù)庫(kù)操作入門(mén)教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- php simplexmlElement操作xml的命名空間實(shí)現(xiàn)代碼
- PHP XML操作類(lèi)DOMDocument
- php中DOMDocument簡(jiǎn)單用法示例代碼(XML創(chuàng)建、添加、刪除、修改)
- PHP使用DOMDocument類(lèi)生成HTML實(shí)例(包含常見(jiàn)標(biāo)簽元素)
- PHP 中 DOMDocument保存xml時(shí)中文出現(xiàn)亂碼問(wèn)題的解決方案
- PHP基于DOMDocument解析和生成xml的方法分析
- PHP實(shí)現(xiàn)動(dòng)態(tài)創(chuàng)建XML文檔的方法
- PHP基于DOM創(chuàng)建xml文檔的方法示例
- PHP創(chuàng)建XML的方法示例【基于DOMDocument類(lèi)及SimpleXMLElement類(lèi)】