1自己拼,XML編碼
成都創(chuàng)新互聯(lián)公司成立與2013年,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目成都網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢想脫穎而出為使命,1280元泰州做網(wǎng)站,已為上家服務(wù),為泰州各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:028-86922220
?php
header('Content-type:text/xml');
echo "?xml version='1.0' encoding='utf-8'";
echo "book";
echo "PHP";
echo "namePHP程序開發(fā)范例寶典/name";
echo "price 單位='元/本'89.00/price";
echo "date2007-09-01/date";
echo "/PHP";
echo "/book";
?
拼接的效果
2從數(shù)據(jù)庫中查詢再拼XML編碼
?php
$dsn="mysql:host=localhost;dbname=test";
try {
$pdo = new PDO($dsn,'root','passwowd'); //初始化一個(gè)PDO對象,就是創(chuàng)建了數(shù)據(jù)庫連接對象$pdo
$query="select * from book"; ? //定義SQL語句
$pdo-query('set names utf8');
$result=$pdo-prepare($query); //準(zhǔn)備查詢語句
$result-execute(); ? ? ? //執(zhí)行查詢語句,并返回結(jié)果集
$arr='';
while($res=$result-fetch()){
$arr.='PHPid'.$res[0].'/idname'.$res[1].'/namedate'.$res[2].'/date'.'price'.$res[3].'/price/PHP';
}
echo "?xml version='1.0' encoding='utf-8'?book".$arr.'/book';
} catch (PDOException $e) {
die ("Error!: ".$e-getMessage()."br");
}
?
拼接的效果
3使用ajax獲取,DOM解析
!DOCTYPE html
html lang="en"
head
meta charset="UTF-8"
titlexml/title
/head
body
script
function check(){
var xhr=new XMLHttpRequest();
xhr.open('GET','xml.php');
xhr.onreadystatechange=function(){
if(xhr.readyState==4 xhr.status==200){
console.log(xhr.responseText);
//初始化 DOM解析對象
var domParser = new DOMParser();
//字符串解碼為對象
var xmlDoc = domParser.parseFromString(xhr.responseText,'text/xml');
//按標(biāo)簽名獲取元素 返回?cái)?shù)組
var elements = xmlDoc.getElementsByTagName('PHP');
//拼接html格式字符串
var str ='trthid/ththname/ththdate/ththprice/th/tr';
for (var i=0;ielements.length;i++){
var id=elements[i].getElementsByTagName('id')[0].firstChild.nodeValue;
var name=elements[i].getElementsByTagName('name')[0].firstChild.nodeValue;
var date=elements[i].getElementsByTagName('date')[0].firstChild.nodeValue;
var price=elements[i].getElementsByTagName('price')[0].firstChild.nodeValue;
str+= 'trtd'+id+'/tdtd'+name+'/tdtd'+date+'/tdtd'+price+'/td/tr';
}
document.getElementById('table2').innerHTML=str;
}
};
xhr.send(null);
}
/script
button onclick="check();"點(diǎn)我/button
table id="table2" border="2" cellspacing="0"
/table
/body
/html
效果
1
2
補(bǔ)充:
使用JSON
1數(shù)據(jù)庫查詢,自己拼?JSON 編碼
?php
$dsn="mysql:host=localhost;dbname=test";
try {
$pdo = new PDO($dsn,'root','password'); //初始化一個(gè)PDO對象,就是創(chuàng)建了數(shù)據(jù)庫連接對象$pdo
$query="select * from book"; ? //定義SQL語句
$pdo-query('set names utf8');
$result=$pdo-prepare($query); //準(zhǔn)備查詢語句
$result-execute(); ? ? ? //執(zhí)行查詢語句,并返回結(jié)果集
$a=$arr='';
while($res=$result-fetch()){
$arr.='{"id":'.'"'.$res[0].'",'.'"name":'.'"'.$res[1].'",'.'"time":'.'"'.$res[2].'",'.'"jia":'.'"'.$res[3].'",'.'"zhe":'.'"'.$res[4].'",'.'"chu":'.'"'.$res[5].'"},';
}
echo $a="[".substr($arr,0,strlen($arr)-1)."]";
} catch (PDOException $e) {
die ("Error!: ".$e-getMessage()."br");
}
?
2數(shù)據(jù)庫查詢,函數(shù)?JSON 編碼
?php
$dsn="mysql:host=localhost;dbname=test";
try {
$pdo = new PDO($dsn,'root','password'); //初始化一個(gè)PDO對象,就是創(chuàng)建了數(shù)據(jù)庫連接對象$pdo
$query="select * from book"; ? //定義SQL語句
$pdo-query('set names utf8');
$result=$pdo-prepare($query); //準(zhǔn)備查詢語句
$result-execute(); ? ? ? //執(zhí)行查詢語句,并返回結(jié)果集
$res=$result-fetchAll();
//JSON 編碼
echo json_encode($res);
} catch (PDOException $e) {
die ("Error!: ".$e-getMessage()."br/");
}
?
效果
3ajax獲取,JSON解析
!DOCTYPE html
html lang="en"
head
meta charset="UTF-8"
titleJSON/title
/head
body
script
function check() {
var XHR = new XMLHttpRequest();
XHR.open('GET','JSON.php');
XHR.onreadystatechange = function (){
if(XHR.readyState == 4 XHR.status ==200){
var books =JSON .parse(XHR.responseText);
var books2='trthid/ththbookname/ththtime/ththprice/ththmarker/ththpublisher/th/tr'
for (var i=0;ibooks.length;i++){
books2+= 'trtd'+(books[i ].id)+'/tdtd'+(books[i ].name)+'/tdtd'+(books[i ].time)+'/tdtd'+(books[i ].jia)+'/tdtd'+(books[i ].zhe)+'/tdtd'+(books[i ].chu)+'/td/tr';
}
document.getElementById('table2').innerHTML=books2;
}
};
XHR.send(null);
}
/script
input type="button" value="點(diǎn)我" onclick="check();"
table id="table2" border="2" cellspacing="0"/table
/body
/html
轉(zhuǎn)成數(shù)組
?php/*** function:使用字符串方式讀XML文件* author:JetWu* date:2016.12.03**/$file = './write_str.xml';$con = file_get_contents($file); //XML標(biāo)簽配置$xmlTag = array( 'starttime', 'endtime', 'school'); $arr = array();foreach($xmlTag as $x) { preg_match_all("/".$x.".*\/".$x."/", $con, $temp); $arr[] = $temp[0];}//去除XML標(biāo)簽并組裝數(shù)據(jù)$data = array();foreach($arr as $key = $value) { foreach($value as $k = $v) { $a = explode($xmlTag[$key].'', $v); $v = substr($a[1], 0, strlen($a[1])-2); $data[$k][$xmlTag[$key]] = $v; }}echo 'pre';print_r($data);
無論是返回 ?json 還是 xml 數(shù)據(jù),區(qū)別僅在于數(shù)據(jù)的格式。
返回 xml 格式數(shù)據(jù)示例如下:
?php
//指示返回?cái)?shù)據(jù)格式為?xml
header('Content-Type:?text/xml');
?
?xml?version="1.0"?encoding="utf-8"??
?php
//構(gòu)造?xml?
//$xmldata?=?"??
//????data??
//???????site_name$site[name]/site_name
//???????........???
//????data";
echo?$xmldata;
?
親手打的,經(jīng)過測試的,采納吧
?php
header("Content-type: text/html; charset=utf-8");
$xml = '?xml version="1.0" encoding="utf-8"?rss version="5.0"list page="1" pagecount="1" pagesize="20" recordcount="1"videolast2014-7-11 12:08:07/lastid19393/idtid7/tidname![CDATA[越軌追擊]]/nametype愛情/typepic;/piclang英語/langarea歐美/areayear2005/yearstate0/statenote![CDATA[HD]]/noteactor![CDATA[克里夫·歐文 詹妮弗·安妮斯頓]]/actordirector![CDATA[米凱爾·哈弗斯特羅姆]]/directordldd flag="jjvod"![CDATA[HD$jjhd://20000|b3a97575c3df592ec08adb93c54a9c2dcf7dc332|越軌追擊HD中字1280高清.rmvb$jjvod]]/dd/dldes![CDATA[他又無法求助于警察,他現(xiàn)在必須找到露辛達(dá),依靠兩個(gè)人的力量奪回曾經(jīng)寧靜的生活。]]/des/video/list/rss';
$result = simplexml_load_string($xml);
//var_dump($result); //可以打印看看結(jié)果如何
$result = object_to_array($result);
//print_r($result['list']['video']);exit;
foreach($result['list']['video'] as $key=$v){
echo $key."=".$v."\n";
}
function object_to_array($obj){
$arr = array();
$_arr = is_object($obj)? get_object_vars($obj) :$obj;
foreach ($_arr as $key = $val){
$val=(is_array($val)) || is_object($val) ? object_to_array($val) :$val;
$arr[$key] = $val;
}
return $arr;
}
?
獲取request中body的字符串?dāng)?shù)據(jù),比如一個(gè)數(shù)組轉(zhuǎn)成xml后,你用post方式給服務(wù)器發(fā)送xml的字符串,服務(wù)器就用file_get_contents('php://input') 去讀取xml格式 然后轉(zhuǎn)成數(shù)組即可
php解析xml報(bào)文的方法是DOMDocument:
解析方法如下:
$xmlstring = XML
?xml version='1.0'?
document
cmd attr='default'login/cmd
loginimdonkey/login
/document
XML;
$dom = new DOMDocument();
$dom-loadXML($xmlstring);
print_r(getArray($dom-documentElement));
function getArray($node) {
$array = false;
if ($node-hasAttributes()) {
foreach ($node-attributes as $attr) {
$array[$attr-nodeName] = $attr-nodeValue;
}
}
if ($node-hasChildNodes()) {
if ($node-childNodes-length == 1) {
$array[$node-firstChild-nodeName] = getArray($node-firstChild);
} else {
foreach ($node-childNodes as $childNode) {
if ($childNode-nodeType != XML_TEXT_NODE) {
$array[$childNode-nodeName][] = getArray($childNode);
}
}
}
} else {
return $node-nodeValue;
}
return $array;
}