note 92323 added to class.simplexmliterator
| From: | ratfactor at gmail dot com | Date: | Mon, 20 Jul 2009 00:08:28 +0000 |
| Subject: | note 92323 added to class.simplexmliterator | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-158483@lists.php.net to get a copy of this message | ||
The documentation is a bit sparse for SimpleXmlIterator. Here is an example showing the use of its
methods. xml2Array and sxiToArray work together to convert an XML document to an associative array
structure.
The contents of cats.xml:
======================================
<cats>
<cat>
<name>Jack</name>
<age>2</age>
<color>grey</color>
<color>white</color>
</cat>
<cat>
<name>Maxwell</name>
<age>12</age>
<color>orange</color>
<color>black</color>
</cat>
</cats>
======================================
<?php
function xml2array($fname){
$sxi = new SimpleXmlIterator($fname, null, true);
return sxiToArray($sxi);
}
function sxiToArray($sxi){
$a = array();
for( $sxi->rewind(); $sxi->valid(); $sxi->next() ) {
if(!array_key_exists($sxi->key(), $a)){
$a[$sxi->key()] = array();
}
if($sxi->hasChildren()){
$a[$sxi->key()][] = sxiToArray($sxi->current());
}
else{
$a[$sxi->key()][] = strval($sxi->current());
}
}
return $a;
}
// Read cats.xml and print the results:
$catArray = xml2array('cats.xml');
print_r($catArray);
?>
Results (reformatted a bit for compactness and clarity):
======================================
Array(
[cat] => Array(
[0] => Array(
[name] => Array( [0] => Jack )
[age] => Array( [0] => 2 )
[color] => Array( [0] => grey,
[1] => white )
)
[1] => Array(
[name] => Array( [0] => Maxwell )
[age] => Array( [0] => 12 )
[color] => Array( [0] => orange
[1] => black )
)
)
)
----
Server IP: 64.71.164.2
Probable Submitter: 24.251.157.169
----
Manual Page -- http://www.php.net/manual/en/class.simplexmliterator.php
Edit -- https://master.php.net/note/edit/92323
Del: integrated -- https://master.php.net/note/delete/92323/integrated
Del: useless -- https://master.php.net/note/delete/92323/useless
Del: bad code -- https://master.php.net/note/delete/92323/bad+code
Del: spam -- https://master.php.net/note/delete/92323/spam
Del: non-english -- https://master.php.net/note/delete/92323/non-english
Del: in docs -- https://master.php.net/note/delete/92323/in+docs
Del: other reasons-- https://master.php.net/note/delete/92323
Reject -- https://master.php.net/note/reject/92323
Search -- https://master.php.net/manage/user-notes.php