array2xml和xml2array,xml与array的互相转计划
[php]
/**
*
* 将简单数组转化为简单的xml
* @param string $data 要进行转化的数组
* @param string $tag 要使用的标签
* @example
* $arr = array(
'rtxAccount'=>'aaron','ipAddr'=>'192.168.0.12',
'conferenceList'=>array('conference'=>
array(
array('conferenceId'=>1212,'conferenceTitle'=>'quanshi 444','smeAccount'=>'bingxu.dong@quanshi.com'),
array('conferenceId'=>454,'conferenceTitle'=>'quanshi meetting','smeAccount'=>'bingxu.dong@quanshi.com'),
array('conferenceId'=>6767,'conferenceTitle'=>'quanshi meetting','smeAccount'=>'bingxu.dong@quanshi.com'),
array('conferenceId'=>232323,'conferenceTitle'=>'quanshi uuu','smeAccount'=>'bingxu.dong@quanshi.com'),
array('conferenceId'=>8989,'conferenceTitle'=>'quanshi meetting','smeAccount'=>'bingxu.dong@quanshi.com'),
array('conferenceId'=>1234343212,'conferenceTitle'=>'quanshi meetting','smeAccount'=>'bingxu.dong@quanshi.com')
)
)
);
转化为:
*/
function array2xml($data,$tag = '')
{
$xml = '';
foreach($data as $key => $value)
{
if(is_numeric($key))
{
if(is_array($value))
{
$xml .= "";
$xml .= array2xml($value);
$xml .="$tag>";
}
else
{
$xml .= "$value$tag>";
}
}
else
{
if(is_array($value))
{
$keys = array_keys($value);
if(is_numeric($keys[0]))
{
$xml .=array2xml($value,$key);
}
else
{
$xml .= "";
$xml .=array2xml($value);
$xml .= "$key>";
}
}
else
{
$xml .= "$value$key>";
}
}
}
return $xml;
}
}
xml2array
[php]
/**
*
* 将简单的xml转化成关联数组
* @param string $xmlString xml字符串
* @example
*
转化之后的关联数组:
Array
(
[conferenceTitle] => IT交流会 www.2cto.com
[startTime] => 2011-12-19 12:00:00
[rtxAccount] => andy1111111
[ipAddr] => 192.168.1.56
[duration] => 120
[conferenceType] => 1
[invitees] => Array
(
[invitee] => Array
(
[0] => Array
(
[rtxAccount] => 被邀请人1的RTX账号
[tel] => 被邀请人1电话号码
)
[1] => Array
(
[rtxAccount] => 被邀请人2的RTX账号
[tel] => 被邀请人2电话号码
)
)
)
)
*/
function xml2array($xmlString = '')
{
$targetArray = array();
$xmlObject = simplexml_load_string($xmlString);
$mixArray = (array)$xmlObject;
foreach($mixArray as $key => $value)
{
if(is_string($value))
{
$targetArray[$key] = $value;
}
if(is_object($value))
{
$targetArray[$key] = xml2array($value->asXML());
}
if(is_array($value))
{
foreach($value as $zkey => $zvalue)
{
if(is_numeric($zkey))
{
$targetArray[$key][] = xml2array($zvalue->asXML());
}
if(is_string($zkey))
{
$targetArray[$key][$zkey] = xml2array($zvalue->asXML());
}
}
}
}
return $targetArray;
}
摘自 andy1219111的专栏
推荐阅读
-
探讨:array2xml和xml2array以及xml与array的互相转化
-
array2xml和xml2array,xml与array的互相转计划
-
array2xml和xml2array,xml与array的互相转计划_PHP教程
-
探讨:array2xml和xml2array以及xml与array的互相转化_php实例
-
探讨:array2xml和xml2array以及xml与array的互相转化
-
探讨:array2xml和xml2array以及xml与array的互相转化_php实例
-
探讨:array2xml和xml2array以及xml与array的互相转化
-
探讨:array2xml和xml2array以及xml与array的互相转化_PHP教程
-
探讨:array2xml和xml2array以及xml与array的互相转化_PHP教程