用php實(shí)現(xiàn)xml與json之間的相互轉(zhuǎn)換:
相關(guān)函數(shù)請查看php手冊。
一、參考xml如下
<?xml version="1.0" encoding="UTF-8"?> <humans> <zhangying> <name>張三</name> <sex>男</sex> <old>26</old> </zhangying> <tank> <name>tank</name> <sex> <hao>yes</hao> <aaaa>no</aaaa> </sex> <old>26</old> </tank> </humans>
二、xml轉(zhuǎn)換成json
利用simplexml
public function xml_to_json($source) { if(is_file($source)){ //傳的是文件,還是xml的string的判斷 $xml_array=simplexml_load_file($source); }else{ $xml_array=simplexml_load_string($source); } $json = json_encode($xml_array); //php5,以及以上,如果是更早版本,請查看JSON.php return $json; }
三、json轉(zhuǎn)換成xml
利用遞歸函數(shù)
public function json_to_xml($source,$charset='utf8') { if(empty($source)){ return false; } //php5,以及以上,如果是更早版本,請查看JSON.php $array = json_decode($source); $xml =''; $xml .= $this->change($array); return $xml; } public function change($source) { $string=""; foreach($source as $k=>$v){ $string .="<".$k.">"; //判斷是否是數(shù)組,或者,對像 if(is_array($v) || is_object($v)){ //是數(shù)組或者對像就的遞歸調(diào)用 $string .= $this->change($v); }else{ //取得標(biāo)簽數(shù)據(jù) $string .=$v; } $string .=""; } return $string; }
上面的方法json_to_xml,可以支持<name>aaaa</name>,不支持<name type='test'>aaaaa</name>看代碼就能看明白.
【相關(guān)教程推薦】
1. php編程從入門到精通全套視頻教程
2. php從入門到精通
3. bootstrap教程
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com