用php實現xml與json之間的相互轉換

php實現xmljson之間的相互轉換:

   

    相關函數請查看php手冊。

   

    一,參考xml如下

   

    <?xml version=1.0encoding=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{

   

    ifis_file$source)){ //傳的是文件,還是xmlstring的判斷

   

    $xml_array=simplexml_load_file$source);

   

    }else{

   

    $xml_array=simplexml_load_string$source);

   

    }

   

    $json = json_encode$xml_array); //php5,以及以上,如果是更早版本,請查看JSON.php

   

    return $json;

   

    }

   

    三,json轉換成xml

   

    利用遞歸函數

   

    public function json_to_xml$source,$charset='utf8‘) {

   

    ifempty$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.>;

   

    //判斷是否是數組,或者,對像

   

    ifis_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>。原因自己分析下。

發佈了326 篇原創文章 · 獲贊 28 · 訪問量 80萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章