多維PHP數組如何轉換成xml格式的資料?

來源:互聯網
上載者:User
php數組 xml

PHP數組是這樣的:
array(4) { ["auth"]=> array(3) {["user"]=> string(8) "customer" ["password"]=> string(8) "password" ["context"]=> string(1) "4" } ["owner"]=> array(2) { ["user"]=> string(9) "customer2" ["context"]=> string(1) "4" } ["language"]=> string(2) "en" ["task"]=> array(1) { ["code"]=> string(4) "0130" } }


轉換成xml格式後的資料格式是這樣的:
customerpassword4customer24en0130


回複討論(解決方案)

 $ar=array( "auth"=> array ("user"=>  "customer" ,"password"=>  "password" ,"context"=>  "4" ) ,"owner"=> array ( "user"=>  "customer2" ,"context"=>  "4" ) ,"language"=>  "en" ,"task"=> array( "code"=>  "0130" ) );$doc = new DOMDocument('1.0','UTF-8');// we want a nice output$doc->formatOutput = true;$root = $doc->createElement('request');$root = $doc->appendChild($root); foreach($ar as $title=>$title_v){   $title = $doc->createElement($title);   $title = $root->appendChild($title);     if(is_array($title_v)){       foreach($title_v as $k=>$v){       $k = $doc->createElement($k);           $k = $title->appendChild($k);   $text = $doc->createTextNode($v);           $text = $k->appendChild($text);   }    }else{       $text = $doc->createTextNode($title_v);       $text = $title->appendChild($text);   }}echo $doc->saveXML();

$ar = array( "auth" => array( "user" => "customer","password" => "password","context" => "4",),"owner" => array( "user" => "customer2","context" => "4",),"language" => "en","task" => array( "code" => "0130",), );$xml = simplexml_load_string('');create($ar, $xml);echo $xml->saveXML();function create($ar, $xml) {foreach($ar as $k=>$v) {if(is_array($v)) {$x = $xml->addChild($k);create($v, $x);}else $xml->addChild($k, $v);}}
 customer password 4 customer2 4 en 0130 
  • 聯繫我們

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