Created
April 11, 2011 11:53
-
-
Save supermethod/913394 to your computer and use it in GitHub Desktop.
Convert a PHP array into XML file using SimpleXML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ArrayToXML | |
{ | |
/** | |
* The main function for converting to an XML document. | |
* Pass in a multi dimensional array and this recrusively loops through and builds up an XML document. | |
* Based on: http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/ | |
* | |
* @param array $data | |
* @param string $rootNodeName - what you want the root node to be - defaultsto data. | |
* @param SimpleXMLElement $xml - should only be used recursively | |
* @return string XML | |
*/ | |
public static function toXml($data, $rootNodeName = 'data', &$xml=null) | |
{ | |
// turn off compatibility mode as simple xml 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( $xml ) ) { | |
$xml = simplexml_load_string(stripslashes("<?xml version='1.0' encoding='utf-8'?><root xmlns: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 xml please! | |
$numeric = false; | |
if ( is_numeric( $key ) ) { | |
$numeric = 1; | |
$key = $rootNodeName; | |
} | |
// delete any char not allowed in XML 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 XML 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 ( ArrayToXML::is_assoc( $value ) || $numeric ) { | |
// older SimpleXMLElement Libraries do not have the addChild Method | |
if (method_exists('SimpleXMLElement','addChild')) | |
{ | |
$node = $xml->addChild( $key, null, 'http://www.lcc.arts.ac.uk/' ); | |
if ($attrs) { | |
foreach($attrs as $key => $attribute) { | |
$node->addAttribute($key, $attribute); | |
} | |
} | |
} | |
}else{ | |
$node =$xml; | |
} | |
// recrusive call. | |
if ( $numeric ) $key = 'anon'; | |
ArrayToXML::toXml( $value, $key, $node ); | |
} else { | |
// older SimplXMLElement Libraries do not have the addChild Method | |
if (method_exists('SimpleXMLElement','addChild')) | |
{ | |
$childnode = $xml->addChild( $key, $value, 'http://www.lcc.arts.ac.uk/' ); | |
if ($attrs) { | |
foreach($attrs as $key => $attribute) { | |
$childnode->addAttribute($key, $attribute); | |
} | |
} | |
} | |
} | |
} | |
// pass back as unformatted XML | |
//return $xml->asXML('data.xml'); | |
// if you want the XML to be formatted, use the below instead to return the XML | |
$doc = new DOMDocument('1.0'); | |
$doc->preserveWhiteSpace = false; | |
@$doc->loadXML( ArrayToXML::fixCDATA($xml->asXML()) ); | |
$doc->formatOutput = true; | |
//return $doc->saveXML(); | |
return $doc->save('data.xml'); | |
} | |
public static function fixCDATA($string) { | |
//fix CDATA tags | |
$find[] = '<![CDATA['; | |
$replace[] = '<![CDATA['; | |
$find[] = ']]>'; | |
$replace[] = ']]>'; | |
$string = str_ireplace($find, $replace, $string); | |
return $string; | |
} | |
/** | |
* Convert an XML document to a multi dimensional array | |
* Pass in an XML document (or SimpleXMLElement object) and this recrusively loops through and builds a representative array | |
* | |
* @param string $xml - XML document - can optionally be a SimpleXMLElement object | |
* @return array ARRAY | |
*/ | |
public static function toArray( $xml ) { | |
if ( is_string( $xml ) ) $xml = new SimpleXMLElement( $xml ); | |
$children = $xml->children(); | |
if ( !$children ) return (string) $xml; | |
$arr = array(); | |
foreach ( $children as $key => $node ) { | |
$node = ArrayToXML::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))))); | |
} | |
} |
I've found almost, if not the same code, here: https://snipt.net/robertbanh/php-array-to-xml/
I was having problems with this code when settings attributes on otherwise empty nodes eg:-
I modified the code as below to resolve
if ( $attr_start === 0 ) {
$attrs[ substr($i, 5) ] = $v;
if(count($value) == 1)
$value="";
else
unset( $value[$i] );
}
`function generateXML($data) {
$title = $data['department'];
$rowCount = count($data['employe']);
//create the xml document
$xmlDoc = new DOMDocument();
$root = $xmlDoc->appendChild($xmlDoc->createElement("employe_info"));
$root->appendChild($xmlDoc->createElement("title",$title));
$root->appendChild($xmlDoc->createElement("totalRows",$rowCount));
$tabUsers = $root->appendChild($xmlDoc->createElement('rows'));
foreach($data['employe'] as $user){
if(!empty($user)){
$tabUser = $tabUsers->appendChild($xmlDoc->createElement('employe'));
foreach($user as $key=>$val){
$tabUser->appendChild($xmlDoc->createElement($key, $val));
}
}
}
header("Content-Type: text/plain");
//make the output pretty
$xmlDoc->formatOutput = true;
//save xml file
$file_name = str_replace(' ', '_',$title).'.xml';
$xmlDoc->save($file_name);
//return xml file name
return $file_name;
}`
You can see this also for converting xml to multidimensional array.
You only need to use generateXML() function and pass data array in it to convert array to XML in PHP.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Man, you're the best. I would made some changes for special cases, but your code is so nice, regards!