note 105813 added to ref.simplexml
| From: | liquidbits at example dot com | Date: | Fri, 16 Sep 2011 21:38:32 +0000 |
| Subject: | note 105813 added to ref.simplexml | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-183227@lists.php.net to get a copy of this message | ||
k.antczak, your recusive function is close, but not quite completeas often simplexml nodes will be
nested inside normal arrays (e.g., <items><item /><item /></items>). Your
script will get the first level, but not any nested deeper.
Changing your condition check solves the problem:
<?php
function xml2array(
$xmlObject,
$out = array())
{
foreach ((array) $xmlObject as $index => $node)
$out[$index] = is_scalar($node) ?
$node:
xml2array($node);
return $out;
}
?>
This renders the sample xml from the SimpleXml Usage page as follows:
array(1) {
["movie"]=>
array(5) {
["title"]=>
string(22) "PHP: Behind the Parser"
["characters"]=>
array(1) {
["character"]=>
array(2) {
[0]=>
array(2) {
["name"]=>
string(9) "Ms. Coder"
["actor"]=>
string(14) "Onlivia Actora"
}
[1]=>
array(2) {
["name"]=>
string(9) "Mr. Coder"
["actor"]=>
string(9) "El ActÃr"
}
}
}
["plot"]=>
string(162) "
So, this language. It's like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
"
["great-lines"]=>
array(1) {
["line"]=>
string(30) "PHP solves all my web problems"
}
["rating"]=>
array(2) {
[0]=>
string(1) "7"
[1]=>
string(1) "5"
}
}
}
----
Server IP: 69.147.83.197
Probable Submitter: 76.27.100.232
----
Manual Page -- http://www.php.net/manual/en/ref.simplexml.php
Edit -- https://master.php.net/note/edit/105813
Del: integrated -- https://master.php.net/note/delete/105813/integrated
Del: useless -- https://master.php.net/note/delete/105813/useless
Del: bad code -- https://master.php.net/note/delete/105813/bad+code
Del: spam -- https://master.php.net/note/delete/105813/spam
Del: non-english -- https://master.php.net/note/delete/105813/non-english
Del: in docs -- https://master.php.net/note/delete/105813/in+docs
Del: other reasons-- https://master.php.net/note/delete/105813
Reject -- https://master.php.net/note/reject/105813
Search -- https://master.php.net/manage/user-notes.php