Convert array to XML string

Uses SimpleXMLElement to convert associative array to XML. Read more.

php
fork add to bundle source
function array_to_xml($array, &$xml = null) { if ( !isset($xml) ) { $xml = new SimpleXMLElement('<?xml version="1.0"?><data></data>'); } foreach( $array as $key => $value ) { if ( is_numeric($key) ) { $key = 'item' . $key; } if ( is_array($value) ) { $node = $xml->addChild($key); array_to_xml($value, $node); } else { $xml->addChild($key, htmlspecialchars($value)); } } return $xml; }

usage

load_function('array_to_xml'); $array = [ 'head' => 'News', 'news' => [ 0 => ['subject' => 'Bla...'], 1 => ['subject' => 'Bla bla...'], ] ]; $xml = array_to_xml($array); echo (string)$xml; // <?xml version="1.0"?> // <data> // <head>News</head> // <news> // <item0><subject>Bla...</subject></item0> // <item1><subject>Bla bla...</subject></item1> // </news> // </data>
← how to use this in app?
create log ...inout