Wednesday, June 13, 2012

xml to array

Here is the function which convert xml data to respective array.

function xmlToArray($xml,$ns=null){
  $a = array();
  for($xml->rewind(); $xml->valid(); $xml->next()) {
    $key = $xml->key();
    if(!isset($a[$key])) { $a[$key] = array(); $i=0; }
    else $i = count($a[$key]);
    $simple = true;
    foreach($xml->current()->attributes() as $k=>$v) {
        $a[$key][$i][$k]=(string)$v;
        $simple = false;
    }
    if($ns) foreach($ns as $nid=>$name) {
      foreach($xml->current()->attributes($name) as $k=>$v) {
         $a[$key][$i][$nid.':'.$k]=(string)$v;
         $simple = false;
      }
    } 
    if($xml->hasChildren()) {
        if($simple) $a[$key][$i] = xmlToArray($xml->current(), $ns);
        else $a[$key][$i]['content'] = xmlToArray($xml->current(), $ns);
    } else {
        if($simple) $a[$key][$i] = strval($xml->current());
        else $a[$key][$i]['content'] = strval($xml->current());
    }
    $i++;
  }
  return $a;
}
This function can be used as follows.
$xml = new SimpleXmlIterator('./a.xml', null, true);
$namespaces = $xml->getNamespaces(true);
$arr = xmlToArray($xml,$namespaces);

1 comment:

Anonymous said...

Hi Uttam,

I am working with a brand to build an engaging content community that covers topics relating to tech news, software, API and mobile apps development.

We’ve taken a read through your blog and we think you’ve done a fantastic job covering topics that our brand's audience would also be interested in covering. It would be great if you could join our community to help educate, inform and converse with those in the tech industry.

If you would like to learn more about this, please send an email to info@atomicreach.com

Thanks,
Annette