多维PHP数组如何转换成xml格式的数据?

WBOY
发布: 2016-06-23 14:23:33
原创
920 人浏览过

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格式后的数据格式是这样的:
<?xml version="1.0" encoding="utf-8"?><request>	<auth>		<user>customer</user>		<password>password</password>		<context>4</context>	</auth>	<owner>		<user>customer2</user>		<context>4</context>	</owner>	<language>en</language>	<task>		<code>0130</code>	</task></request>
登录后复制


回复讨论(解决方案)

 $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('<request />');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);	}}
登录后复制
<?xml version="1.0" ?> <request>	<auth>		<user>customer</user> 		<password>password</password> 		<context>4</context> 	</auth>	<owner>		<user>customer2</user> 		<context>4</context> 	</owner>	<language>en</language> 	<task>		<code>0130</code> 	</task></request>
登录后复制
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板