2015-12-11 115 views
-1

我有數組像下面我如何轉換陣列SimpleXMLElement對象

Array 
(
    [@attributes] => Array 
     (
      [Id] => 925343664 
      [FloorplanID] => 617454 
      [BuildingID] => 
     ) 

    [Unit] => Array 
     (
     ) 

    [Comment] => Array 
     (
     ) 

    [Availability] => Array 
     (
      [VacancyClass] => Occupied 
      [MadeReadyDate] => Array 
       (
        [@attributes] => Array 
         (
          [Month] => 1 
          [Day] => 24 
          [Year] => 2016 
         ) 

       ) 

     ) 

) 

我想這個數組轉換中SimpleXMLElement對象像下面

SimpleXMLElement Object 
(
    [@attributes] => Array 
     (
      [Id] => 925832659 
      [FloorplanID] => 617454 
      [BuildingID] => 
     ) 

    [Unit] => SimpleXMLElement Object 
     (
     ) 

    [Comment] => SimpleXMLElement Object 
     (
     ) 

    [Availability] => SimpleXMLElement Object 
     (
      [VacancyClass] => Occupied 
      [MadeReadyDate] => SimpleXMLElement Object 
       (
        [@attributes] => Array 
         (
          [Month] => 1 
          [Day] => 12 
          [Year] => 2016 
         ) 

       ) 

     ) 

) 

我嘗試了一些谷歌上搜索,但我沒有找不到任何解決方案 我該怎麼做?任何人都可以有這個解決方案?

+3

的可能的複製[如何數組轉換爲SimpleXML的(http://stackoverflow.com/questions/1397036/how-to-convert-array-to-simplexml ) – Vineet1982

+0

這不適用於我 – Nikul

+1

您是否嘗試過使用PHP手冊中的可能解決方案? http://php.net/manual/en/book.simplexml.php#101949 – maxhb

回答

1
$xml = '<?xml version='1.0' standalone='yes'?>'; 
function rekursiveArrayToXML($array, &$xml, $name = 'root') { 
$xml .= "$<$name"; 
if (is_array($array) AND isset($array['@attributes'])) { 
    foreach ($array['@attributes'] as $k => $v) { 
     $xml .= " $k=\"$v\""; 
    } 
    unset($array['@attributes']); 
} 
$xml .= ">"; 
if (is_array($array)) { 
    foreach ($array as $k => $v) { 
     rekursiveArrayToXML($v, $xml, $k); 
    } 
} else { 
    $xml .= $array; 
} 
    $xml .= "</$name>\n"; 
} 

$array = array(
    '@attributes' => Array 
    (
      'Id' => 925343664, 
      'FloorplanID' => 617454, 
      'BuildingID' => 0 
    ), 
    'Unit' => Array(), 
    'Comment' => Array(), 
    'Availability' => Array 
    (
      'VacancyClass' => 'Occupied', 
      'MadeReadyDate' => Array 
      (
        '@attributes' => Array 
        (
          'Month' => 1, 
          'Day' => 24, 
          'Year' => 2016, 
        ) 

      ) 

    ) 
); 

rekursiveArrayToXML($array, $xml); 

var_export(simplexml_load_string($xml)); 

類似的東西;)