php xml 轉換 數組

class XmlUtils
{
    public static function xmlStr2Array($str)
    {
        $sxe = new SimpleXMLElement($str);
        return  self::xml2Array($sxe);
    }

    private static function xml2Array($sxe)
    {
        $arr = array();
        if($sxe instanceof SimpleXMLElement) {
            $name = $sxe->getName();
            if(!empty($name)) {
                    $arr[$name] = array();
                $attrs = $sxe->attributes();
                foreach($attrs as $key => $value) {
                    if(!empty($key)) {
                        $arr[$name]['attr_'.$key] = (string)$value;
                    }
                }
                $children = $sxe->children();
                if(is_null($children) || count($children) == 0) {
                    //echo '<br>' . trim((string)($sxe->asXML())) . '<br>';
//                    if(0 == count($attrs)) {
//                        $arr[$name] = trim((string)($sxe->asXML()));
//                    } else {
                        $arr[$name]['value'] = trim((string)($sxe->asXML()));
//                    }
                } else {
                    foreach($children as $child) {
                        $childName = $child->getName();
                        if(!empty($childName)) {
                            $childArr = $this->xml2Array($child);
                            $key = $childName;
                            $i = 1;
                            while(array_key_exists($key, $arr[$name])) {
                                $key = $childName . $i;
                            }
                            $arr[$name][$key] = $childArr[$childName];
                        }
                    }
                }
            }
        }
        return $arr;
    }
}
$result = XmlUtils::xmlStr2Array($result);
?>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章