php数组与 互转

class ArrayTo 
{
    /**
     * The main function for converting to an   document.
     * Pass in a multi dimensional array and this recrusively loops through and builds up an   document.
     *  d on: http://snipplr.com/view/3491/convert-php-array-to- -or-simple- - -if-you-wish/
	 * 
     * @param array $data
     * @param string $rootNodeName - what you want the root node to be - defaultsto data.
     * @param Simple Element $  - should only be used recursively
     * @return string  
     */
    public static function to ($data, $rootNodeName = \'data\', &$ =null)
    {
        // turn off compatibility mode as simple   throws a wobbly if you don\'t.
    if ( ini_get(\'zend.ze1_compatibility_mode\') == 1 ) ini_set ( \'zend.ze1_compatibility_mode\', 0 );
    if ( is_null( $  ) ) {
    	 $  = simple _load_string(stripslashes(\"<?  version=\'1.0\' encoding=\'utf-8\'?><root  ns:example=\'http://example.namespace.com\' version=\'1.0\'></root>\"));
	}

    // loop through the data passed in.
    foreach( $data as $key => $value ) {

        // no numeric keys in our   please!
        $numeric = false;
        if ( is_numeric( $key ) ) {
            $numeric = 1;
            $key = $rootNodeName;
        }

        // delete any char not allowed in   element names
        $key = preg_replace(\'/[^a-z0-9\\-\\_\\.\\:]/i\', \'\', $key);
		
		//check to see if there should be an attribute added (expecting to see _id_)
		$attrs = false;

		//if there are attributes in the array (denoted by attr_**) then add as   attributes
		if ( is_array( $value ) ) {
			foreach($value as $i => $v ) {
				$attr_start = false;
				$attr_start = stripos($i, \'attr_\');
				if ($attr_start === 0) {
					$attrs[substr($i, 5)] = $v; unset($value[$i]);
				}
			}
		}
		  
		
        // if there is another array found recursively call this function
        if ( is_array( $value ) ) {

            if ( ArrayTo ::is_assoc( $value ) || $numeric ) {

                // older Simple Element Libraries do not have the addChild Method
                if (method_exists(\'Simple Element\',\'addChild\'))
                {
                    $node = $ ->addChild( $key, null, \'http://www.lcc.arts.ac.uk/\' );
					if ($attrs) {
						foreach($attrs as $key => $attribute) {
							$node->addAttribute($key, $attribute);
						}
					}
                }

            }else{
                $node =$ ;
            }

            // recrusive call.
            if ( $numeric ) $key = \'anon\';
            ArrayTo ::to ( $value, $key, $node );
        } else {

                // older Simpl Element Libraries do not have the addChild Method
                if (method_exists(\'Simple Element\',\'addChild\'))
                {
                    $childnode = $ ->addChild( $key, $value, \'http://www.lcc.arts.ac.uk/\' );
					if ($attrs) {
						foreach($attrs as $key => $attribute) {
							$childnode->addAttribute($key, $attribute);
						}
					}
                }
        }
    }

	// pass back as unformatted  
	//return $ ->as (\'data. \');

	// if you want the   to be formatted, use the below instead to return the  
	    $doc = new DOMDocument(\'1.0\');
	    $doc->preserveWhiteSpace = false;
	    @$doc->load ( ArrayTo ::fixCDATA($ ->as ()) );
	    $doc->formatOutput = true;
	    //return $doc->save ();
	    return $doc->save(\'data. \');
	}

	public static function fixCDATA($string) {
		//fix CDATA tags
		$find[]     = \'&lt;![CDATA[\';
		$replace[] = \'<![CDATA[\';
		$find[]     = \']]&gt;\';
		$replace[] = \']]>\';	
		
		$string = str_ireplace($find, $replace, $string);	
		return $string;
	}

/**
 * Convert an   document to a multi dimensional array
 * Pass in an   document (or Simple Element  ) and this recrusively loops through and builds a representative array
 *
 * @param string $  -   document - can optionally be a Simple Element  
 * @return array ARRAY
 */
	public static function toArray( $  ) {
	    if ( is_string( $  ) ) $  = new Simple Element( $  );
	    $children = $ ->children();
	    if ( !$children ) return (string) $ ;
	    $arr = array();
	    foreach ( $children as $key => $node ) {
	        $node = ArrayTo ::toArray( $node );
	
	        // support for \'anon\' non-associative arrays
	        if ( $key == \'anon\' ) $key = count( $arr );
	
	        // if the node is already set, put it into an array
	        if ( isset( $arr[$key] ) ) {
	            if ( !is_array( $arr[$key] ) || $arr[$key][0] == null ) $arr[$key] = array( $arr[$key] );
	            $arr[$key][] = $node;
	        } else {
	            $arr[$key] = $node;
	        }
	    }
	    return $arr;
	}
	
	// determine if a variable is an associative array
	public static function is_assoc( $array ) {
	    return (is_array($array) && 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
	}
}
收藏 打印