探讨:array2xml和xml2array以及xml与array的互相转化(2)


/**
  *
  * 将简单的xml转化成关联数组
  * @param string $xmlString  xml字符串
  * @example
  * <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<RTXConferenceReqDTO>
 <conferenceTitle>IT交流会</conferenceTitle>
 <startTime>2011-12-19 12:00:00</startTime>
 <rtxAccount>andy1111111</rtxAccount>
 <ipAddr>192.168.1.56</ipAddr>
 <duration>120</duration>
 <conferenceType>1</conferenceType>
 <invitees>
  <invitee>
   <rtxAccount>被邀请人1的RTX账号</rtxAccount>
   <tel>被邀请人1电话号码</tel>
  </invitee>
  <invitee>
   <rtxAccount>被邀请人2的RTX账号</rtxAccount>
   <tel>被邀请人2电话号码</tel>
  </invitee>
 </invitees>
</RTXConferenceReqDTO>
转化之后的关联数组:
Array
(
    [conferenceTitle] => IT交流会
    [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;

 }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/8f9fd0a8a6ee383bc8b8dc14a5a53a51.html