PHP XML 2 Array Function





18
Date Submitted Mon. Oct. 9th, 2006 2:58 PM
Revision 1 of 1
Scripter wiz1705
Tags Array | PHP | XML
Comments 2 comments
I've seen XML 2 Array functions done in other ways but this is the shortest implementation I've seen yet. I didnt write it myself though, but I thought I'd submit it for common good of this site. It uses regex and works prefectly.
function xml2array($xml) {
        $xmlary = array();
               
        $reels = '/<(\w+)\s*([^\/>]*)\s*(?:\/>|>(.*)<\/\s*\\1\s*>)/s';
        $reattrs = '/(\w+)=(?:"|\')([^"\']*)(:?"|\')/';

        preg_match_all($reels, $xml, $elements);

        foreach ($elements[1] as $ie => $xx) {
                $xmlary[$ie]["name"] = $elements[1][$ie];
               
                if ($attributes = trim($elements[2][$ie])) {
                        preg_match_all($reattrs, $attributes, $att);
                        foreach ($att[1] as $ia => $xx)
                                $xmlary[$ie]["attributes"][$att[1][$ia]] = $att[2][$ia];
                }

                $cdend = strpos($elements[3][$ie], "<");
                if ($cdend > 0) {
                        $xmlary[$ie]["text"] = substr($elements[3][$ie], 0, $cdend - 1);
                }

                if (preg_match($reels, $elements[3][$ie]))
                        $xmlary[$ie]["elements"] = xml2array($elements[3][$ie]);
                else if ($elements[3][$ie]) {
                        $xmlary[$ie]["text"] = $elements[3][$ie];
                }
        }

        return $xmlary;
}

Zachary Howe

autoignition.net

Comments

Comments Yet Another XML2Array
Fri. May. 15th, 2009 9:08 AM    Beginner ChronoFish
Comments wow...
Sat. Oct. 14th, 2006 4:37 PM    Newbie Patrick

Voting