本文實例講述了php實現xml與json之間的相互轉換功能。分享給大家供大家參考,具體如下:
用php實現xml與json之間的相互轉換:
相關函數請查看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轉換成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.phpreturn $json;}三、json轉換成xml
利用遞歸函數
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.">";//判斷是否是數組,或者,對像if(is_array($v) || is_object($v)){//是數組或者對像就的遞歸調用$string .= $this->change($v);}else{//取得標簽數據$string .=$v;}$string .="";}return $string;}上面的方法json_to_xml,可以支持<name>aaaa</name>,不支持<name type='test'>aaaaa</name>看代碼就能看明白.
希望本文所述對大家PHP程序設計有所幫助。
新聞熱點
疑難解答
圖片精選