-1

I have array like below

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
                        )

                )

        )

)

I want to convert this array in to SimpleXMLElement Object like below

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
                        )

                )

        )

)

I tried with some googling but i didn't find any solution How can i do this ? Can anyone have solution for this ?

Nikul
  • 465
  • 1
  • 8
  • 24

1 Answers1

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));

something like that ;)

JustOnUnderMillions
  • 3,741
  • 9
  • 12