php 數組 xml json xml相互轉換的方法

來源:互聯網
上載者:User
首先,來看array->xml。$value) {

首先,來看array->xml。

function ia2xml($array) { $xml=""; foreach ($array as $key=>$value) { if (is_array($value)) { $xml.="<$key>".ia2xml($value).""; } else { $xml.="<$key>".$value.""; } } return $xml; }

return simplexml_load_string("<$tag>".ia2xml($array).""); }

$test['type']='lunch'; $test['time']='12:30'; $test['menu']=array('entree'=>'salad', 'maincourse'=>'steak');

echo array2xml($test,"meal")->asXML(); ?>

其次,xml->array。方法一:function xml2phpArray($xml,$arr){ $iter = 0; foreach($xml->children() as $b){ $a = $b->getName(); if(!$b->children()){ $arr[$a] = trim($b[0]); }else{ $arr[$a][$iter] = array(); $arr[$a][$iter] = xml2phpArray($b,$arr[$a][$iter]); $iter++; } } return $arr; }

$xml = <<GeorgeJohnReminderDon't forget the meeting!ccceeeXML;

print_r(xml2phpArray(simplexml_load_string ( $xml ),array()));

方法二:function XML2Array ( $xml , $recursive = false ){ if ( ! $recursive ) { $array = simplexml_load_string ( $xml ) ; } else { $array = $xml ; } $newArray = array () ; $array = ( array ) $array ; foreach ( $array as $key => $value ) { $value = ( array ) $value ; if ( isset ( $value [ 0 ] ) ) { $newArray [ $key ] = trim ( $value [ 0 ] ) ; } else { $newArray [ $key ] = XML2Array ( $value , true ) ; } } return $newArray ;}

$xml = <<GeorgeJohnReminderDon't forget the meeting!ccceeeXML;

print_r(XML2Array($xml));

來看json->array。json_decode($json,true);//第二個參數為true時 即為array$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';var_dump(json_decode($json));var_dump(json_decode($json, true));

最後,來看array->jsonjson_encode 數組->json$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);echo json_encode($arr);

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.