PHP 8.5.0 Alpha 2 available for testing

Voting

: eight minus three?
(Example: nine)

The Note You're Voting On

ajnsit dot NOSPAM at gmail dot com
14 years ago
Here's a simple function to convert an XML string to an array -

<?php
// PHP5.3 and above only
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)

<< Back to user notes page

To Top