S
S
siroper2020-05-26 16:50:29
PHP
siroper, 2020-05-26 16:50:29

Multidimensional SimpleXMLElement object to php array - how?

Hello. I'm trying to output a multidimensional SimpleXMLElement to an array. I use the function:

function xmlToArray($xml) {
  $xml = (array) $xml;

  if(empty($xml)) {
    return null;
  }

  foreach ($xml as $key=>$val) {
    if ($val instanceof SimpleXMLElement) {
      $xml[$key] = xmlToArray($val);
    } elseif (empty($val)) {
      $xml[$key] = null;
    }
  }

  return $xml;
}


It helps but only for the first levels of the array. Then comes the same SimpleXMLElement Object

Answer example (integration with crm, xml code goes through api).

Array
(
    [users] => Array
        (
            [@attributes] => Array
                (
                    [totalCount] => 10
                    [count] => 10
                )

            [user] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [id] => 5911138
                            [name] => Администратор площадки
                            [lastName] => SimpleXMLElement Object
                                (
                                )

                            [login] => Admin
                            [email] => [email protected]
                            [jabber] => SimpleXMLElement Object
                                (
                                )


Those. the first 3 levels were converted to an array using the above function, but the rest were not.
How to solve this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
ThunderCat, 2020-05-26
@ThunderCat

The classic solution straight from the manual:

$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
which, however, has several side effects, such as not seeing [CDATA[ ]]nodes or seeing them as empty elements...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question