Search code examples
phpxml

How to convert XML into array in PHP?


I want to convert below XML to PHP array. Any suggestions on how I can do this?

<aaaa Version="1.0">
   <bbb>
     <cccc>
       <dddd Id="id:pass" />
       <eeee name="hearaman" age="24" />
     </cccc>
   </bbb>
</aaaa>

Solution

  • Another option is the SimpleXML extension (I believe it comes standard with most php installs.)

    http://php.net/manual/en/book.simplexml.php

    The syntax looks something like this for your example

    $xml = new SimpleXMLElement($xmlString);
    echo $xml->bbb->cccc->dddd['Id'];
    echo $xml->bbb->cccc->eeee['name'];
    // or...........
    foreach ($xml->bbb->cccc as $element) {
      foreach($element as $key => $val) {
       echo "{$key}: {$val}";
      }
    }