Here's a simple function to convert an XML string to an array -
<?php
function parse($str) {
$f = function($iter) {
foreach($iter as $key=>$val)
$arr[$key][] = ($iter->hasChildren())?
call_user_func (__FUNCTION__, $val)
: strval($val);
return $arr;
};
return $f(new SimpleXmlIterator($str, null));
}
?>
PHP 5.2 and below do not have anonymous functions.
But you can create a helper function to achieve the same thing -
<?php
function parse($str) {
return parseHelper(new SimpleXmlIterator($str, null));
}
function parseHelper($iter) {
foreach($iter as $key=>$val)
$arr[$key][] = ($iter->hasChildren())?
call_user_func (__FUNCTION__, $val)
: strval($val);
return $arr;
}
?>
Using it is straightforward enough -
<?php
$xml = '
<movies>
<movie>abcd</movie>
<movie>efgh</movie>
<movie>hijk</movie>
</movies>';
var_dump(parse($xml));
?>
This will output -
array
'movie' =>
array
0 => string 'abcd' (length=4)
1 => string 'efgh' (length=4)
2 => string 'hijk' (length=4)