Rated an average of 4.5 stars by 2 people

Array to Xml

Script Details:
Added on August 8, 2011 by mario. Last modified August 8, 2011.
mario accreditted the script to "mario deluna."

Description:
Converts an Array to XML

Tags: array, xml

Code:

<?php
# Snippet from PHP Share: http://www.phpshare.org

/* (c) by Clan - Cats . com */

// Example
// Set simple XML object
ccXML:: $xml simplexml_load_string("<? xml version = '1 . 0' encoding = 'utf - 8'?><myXML />");
// Set data array
ccXML::addArray( array(
  
'foo' => bar,
  
'foo' => array(
    
'fooValue',
    
'barValue'
  
),
  
'captian' => array(
    
'name' => 'awesome',
    
'points' => '42'
  ),
));
// print
print ccXML::get_xml();

/* Returns 
<myXML>
  <foo>fooValue</foo>
  <foo>barValue</foo>
  <captian>
    <name>awesome</name>
    <points>42</points>
  </captian>
</myXML>
 */


// CCXML
class ccXML {
    public static 
$xml;

    public static function 
addArray$arr$xml NULL$masterKey NULL ) {
        
        if ( !isset( 
$xml ) ){
            
$xml ccXML::$xml;
        }
        
        foreach ( 
$arr as $key => $value ) {
            
            if ( 
is_array$value ) ) {
                if ( 
is_numeric$key ) ) {
                    
$key $masterKey;
                }
                if ( !isset( 
$value[0] ) ) {
                    
$node $xml->addChild$key );
                    
ccXML::addArray$value$node$key );
                } else {
                    
$xml ccXML::addArray$value$xml$key );
                }
            } else {
                if ( 
is_numeric$key ) ) {
                    
$xml->addChild$masterKey$value );
                } else {
                
//$value = htmlentities( $value );
                    
$xml->addChild$key$value );
                }
            }
        }
        return 
$xml;
    }
    
    public static function 
get_xml() {
        return 
ccXML::$xml->asXML();
    }
}
?>

Review this PHP Script:

Rating:

Comments:




Comments

Login

User:
Pass:

Register

Not a member? Register today and receive the many free benefits of being a member!

Advertisements