手机浏览 RSS 2.0 订阅 膘叔的简单人生 , 腾讯云RDS购买 | 超便宜的Vultr , 注册 | 登陆
浏览模式: 标准 | 列表Tag:xml2array

xml2array 和 array2xml

这是一个简单的方法,其实是两种方法的其中一种:xml2array 和 array2xml 中的一种啦。
但因为array2xml的时候,没有办法做到更好的把attributes做到更好,因此,就折腾了一些简单的处理方法:
array2xml是hightman的方法的简版。我自己改了一些:

PHP代码
  1. function array2xml($var$type = 'root'$tag = '') {  
  2.    $ret = '';  
  3.    if (!is_int($type)) {  
  4.        if ($tag)  
  5.            return array2xml(array($tag => $var), 0, $type); else {  
  6.            $tag .= $type;  
  7.            $type = 0;  
  8.        }  
  9.    }  
  10.    $level = $type;  
  11.    $indent = str_repeat("\t"$level);  
  12.    if (!is_array($var)) {  
  13.        $ret .= $indent . '<' . $tag;  
  14.        $var = strval($var);  
  15.        if ($var == '') {  
  16.            $ret .= ' />';  
  17.        } else if (!preg_match('/[^0-9a-zA-Z@\._:\/-]/'$var)) {  
  18.            $ret .= '>' . $var . '</' . $tag . '>';  
  19.        } else {  
  20.            $ret .= "><![CDATA[{$var}]]></{$tag}>";  
  21.        }  
  22.        //                if (strpos($var, "\n") === false){  
  23.        //                $ret .= '><![CDATA[' . $var . ']]></' . $tag . '>';  
  24.        //            } else  
  25.        $ret .= "\n";  
  26.    } else if (!(is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) && !emptyempty($var)) {  
  27.        foreach ($var as $tmp)  
  28.            $ret .= array2xml($tmp$level$tag);  
  29.    } else {  
  30.        $ret .= $indent . '<' . $tag;  
  31.        if ($level == 0)  
  32.            $ret .= '';  
  33.        if (isset($var['@attributes'])) {  
  34.            foreach ($var['@attributes'as $k => $v) {  
  35.                if (!is_array($v)) {  
  36.                    $ret .= sprintf(' %s="%s"'$k$v);  
  37.                }  
  38.            }  
  39.            unset($var['@attributes']);  
  40.        }  
  41.        $ret .= ">\n";  
  42.        foreach ($var as $key => $val) {  
  43.            $ret .= array2xml($val$level + 1, $key);  
  44.        }  
  45.        $ret .= "{$indent}</{$tag}>\n";  
  46.    }  
  47.    return $ret;  

在其中强加了attributes。比较恶心的方法啦。。
然后xml2array,其实以前写过,但写的不太好,所以我这次抄的是ibm的网站上的xml2json中的代码:

PHP代码
  1. define ("DEBUG", false);  
  2. // Maximum Recursion Depth that we can allow.  
  3. define ("MAX_RECURSION_DEPTH_ALLOWED", 25);  
  4. // An empty string  
  5. define ("EMPTY_STR""");  
  6. // SimpleXMLElement object property name for attributes  
  7. define ("SIMPLE_XML_ELEMENT_OBJECT_PROPERTY_FOR_ATTRIBUTES""@attributes");  
  8. // SimpleXMLElement object name.  
  9. define ("SIMPLE_XML_ELEMENT_PHP_CLASS""SimpleXMLElement");  
  10.     /** 
  11.      * @static 
  12.      * @param $simpleXmlElementObject 
  13.      * @param int $recursionDepth 
  14.      * @return array|null|string 
  15.      */  
  16.     public static function xml2array($simpleXmlElementObject$getAttributes = false , &$recursionDepth = 0 ) {  
  17.         // Keep an eye on how deeply we are involved in recursion.  
  18.         if ($recursionDepth > MAX_RECURSION_DEPTH_ALLOWED) {  
  19.             // Fatal error. Exit now.  
  20.             return (null);  
  21.         }  
  22.         if ($recursionDepth == 0) {  
  23.             if (get_class($simpleXmlElementObject) != SIMPLE_XML_ELEMENT_PHP_CLASS) {  
  24.                 // If the external caller doesn't call this function initially  
  25.                 // with a SimpleXMLElement object, return now.  
  26.                 return (null);  
  27.             } else {  
  28.                 // Store the original SimpleXmlElementObject sent by the caller.  
  29.                 // We will need it at the very end when we return from here for good.  
  30.                 $callerProvidedSimpleXmlElementObject = $simpleXmlElementObject;  
  31.             }  
  32.         } // End of if ($recursionDepth == 0) {  
  33.         if (get_class($simpleXmlElementObject) == SIMPLE_XML_ELEMENT_PHP_CLASS) {  
  34.             // Get a copy of the simpleXmlElementObject  
  35.             $copyOfsimpleXmlElementObject = $simpleXmlElementObject;  
  36.             // Get the object variables in the SimpleXmlElement object for us to iterate.  
  37.             $simpleXmlElementObject = get_object_vars($simpleXmlElementObject);  
  38.         }  
  39.         // It needs to be an array of object variables.  
  40.         if (is_array($simpleXmlElementObject)) {  
  41.             // Initialize the result array.  
  42.             $resultArray = array();  
  43.             // Is the input array size 0? Then, we reached the rare CDATA text if any.  
  44.             if (count($simpleXmlElementObject) <= 0) {  
  45.                 // Let us return the lonely CDATA. It could even be  
  46.                 // an empty element or just filled with whitespaces.  
  47.                 return (trim(strval($copyOfsimpleXmlElementObject)));  
  48.             }  
  49.             // Let us walk through the child elements now.  
  50.             foreach ($simpleXmlElementObject as $key => $value) {  
  51.                 // When this block of code is commented, XML attributes will be  
  52.                 // added to the result array.  
  53.                 // Uncomment the following block of code if XML attributes are  
  54.                 // NOT required to be returned as part of the result array.  
  55.                 /* 
  56.           if((is_string($key)) && ($key == SIMPLE_XML_ELEMENT_OBJECT_PROPERTY_FOR_ATTRIBUTES)) { 
  57.                   continue; 
  58.                 } 
  59.                 */  
  60.                 // Let us recursively process the current element we just visited.  
  61.                 // Increase the recursion depth by one.  
  62.                 $recursionDepth++;  
  63.                 if($key == '@attributes' && $getAttributes == true){  
  64.                     foreach(self::xml2array($value,$getAttributes$recursionDepthas $k=>$v){  
  65.                         $resultArray[$k]=$v;  
  66.                     }  
  67.                 }else{  
  68.                     $resultArray[$key] = self::xml2array($value,$getAttributes$recursionDepth);  
  69.                 }  
  70.                 // Decrease the recursion depth by one.  
  71.                 $recursionDepth--;  
  72.             } // End of foreach($simpleXmlElementObject as $key=>$value) {  
  73.             if ($recursionDepth == 0) {  
  74.                 // That is it. We are heading to the exit now.  
  75.                 // Set the XML root element name as the root [top-level] key of  
  76.                 // the associative array that we are going to return to the caller of this  
  77.                 // recursive function.  
  78.                 $tempArray = $resultArray;  
  79.                 $resultArray = array();  
  80.                 $resultArray[$callerProvidedSimpleXmlElementObject->getName()] = $tempArray;  
  81.             }  
  82.             return ($resultArray);  
  83.         } else {  
  84.             // We are now looking at either the XML attribute text or  
  85.             // the text between the XML tags.  
  86.             return (trim(strval($simpleXmlElementObject)));  
  87.         } // End of else  
  88.     }  

改过其中的几行代码,否则会报错,改了哪几行我忘了。。官网地址是:http://www.ibm.com/developerworks/xml/library/x-xml2jsonphp/

这里还有一个:http://www.zenme.org/?action=show&id=270,可以参考一下

Tags: xml2array