Converting XML to PHP Array

Posted by & filed under PHP.

Base on “ratfactor at gmail dot com notes” at http://php.net/manual/en/class.simplexmliterator.php

class XMLtoArray {
    
    public static function xml2array($fname) {
        $sxi = new SimpleXmlIterator($fname, null, true);
        return self::sxiToArray($sxi);
    }

    public static function sxiToArray($sxi) {
        $a = array();
        for ($sxi->rewind(); $sxi->valid(); $sxi->next()) {
            if (!array_key_exists($sxi->key(), $a)) {
                $a[$sxi->key()] = array();
            }
            if ($sxi->hasChildren()) {
                $a[$sxi->key()][] = self::sxiToArray($sxi->current());
            } else {
                $a[$sxi->key()][] = strval($sxi->current());
            }
        }
        return $a;
    }
}

// Read cats.xml and print the results:
$catArray = XMLtoArray::xml2array('cats.xml');
print_r($catArray);