As a developer, it is common to search the web for an existing (open source) code snippet to re-use for an application, but it is rare for the developer to just copy code online and use it straight in their application without modifying it first.
I am one of many developers who like to save time if possible by using open source code if coding from scratch takes longer than a couple of minutes, but there are times when one cannot be found. I ran into such situation when I wanted a function that converts an XML string into an array. Unfortunately, most are overly complicated for what I wanted, so I decided to create my own and share with the world. The following function converts XML strings into a PHP array while retaining the level depths of the XML but all attributes are ignored.
/**
* Simple XML to array conversion.
*
* Warning: Ignores all attributes!
*
* Link: http://18.237.84.250/?p=79
*
* @author johnro
* @param xml $string
*/
function convert_xml_to_array($string) {
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($parser, $string, $vals, $index);
xml_parser_free($parser);
$array = array();
$curr = &$array;
$levels = array();
$item = array();
foreach($vals as $val) {
switch($val['type']) {
case 'open':
if(!empty($item)) {
foreach($item as $key => $value) {
$curr[$key] = $value;
}
$item = array();
}
$levels[$val['level']] = &$curr;
$curr[$val['tag']] = array();
$curr = &$curr[$val['tag']];
break;
case 'complete':
$item[$val['tag']] = $val['value'];
break;
case 'close':
if(!empty($item)) {
foreach($item as $key => $value) {
$curr[$key] = $value;
}
$item = array();
}
$curr = &$levels[$val['level']];
break;
}
}
return $array;
}
The following is a sample XML:
Everyone
John
Test
cool
cat
dog
piano
flute
which gets converted to the following array
array (
'note' =>
array (
'to' => 'Everyone',
'from' => 'John',
'heading' => 'Test',
'other' =>
array (
'type' => 'cool',
'words' =>
array (
'first' => 'cat',
'second' =>
array (
),
),
),
),
)
To complete this library, I have also included a function to convert the array back to XML string.
/**
* Simple array to XML conversion.
*
* Warning: Ignores all attributes!
*
* Link: http://18.237.84.250/?p=79
*
* @author johnro
* @param array $array
* @param string $namespace
*/
function convert_array_to_xml($array, $namespace = '') {
$xml = '';
foreach($array as $key => $value) {
if(is_array($value)) {
$value = convert_array_to_xml($value);
}
$xml .= "$value";
}
return $xml;
}
Feel free to use and any word of advice is appreciated.
Leave a comment