php xml與json間的相互轉換例子

來源:互聯網
上載者:User

今天在網上想找個將xml轉成json的方法,找了半天沒找到,找到了,根本沒有什麼用,有一個service_JSON說的挺像真的,找開後就一個JSON.php,php5.0以後已經把它加進來,json_decode和json_encode。想走捷徑的,唉,靠人不如靠已。以下是我寫的一個方法

一,參考xml檔案如下
 

 代碼如下 複製代碼
<?xml version="1.0" encoding="UTF-8"?> 
  <humans> 
  <zhangying> 
  <name>張映</name> 
  <sex>男</sex> 
  <old>28</old> 
  </zhangying> 
  <tank> 
  <name>tank</name> 
  <sex> 
 <hao>yes</hao> 
 <aaaa>no</aaaa> 
 </sex> 
  <old>28</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.php 
    return $json; 

三,json

轉換成xml

利用遞迴函式

 代碼如下 複製代碼
 
public function json_to_xml($source,$charset='utf8') { 
    if(emptyempty($source)){ 
        return false; 
    } 
    $array = json_decode($source);  //php5,以及以上,如果是更早版本,?下?JSON.php 
    $xml  ='<!--l version="1.0" encoding="'.$charset.'-->'; 
    $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>看代碼就能看明白。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.