php實現(xiàn)xml與json之間的相互轉(zhuǎn)換功能實例

字號:


    本文實例講述了php實現(xiàn)xml與json之間的相互轉(zhuǎn)換功能。分享給大家供大家參考,具體如下:
    用php實現(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{
    //取得標簽數(shù)據(jù)
    $string .=$v;
    }
    $string .="";
    }
    return $string;
    }
    上面的方法json_to_xml,可以支持<name>aaaa</name>,不支持<name type='test'>aaaaa</name>看代碼就能看明白.
    希望本文所述對大家PHP程序設(shè)計有所幫助。