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 )
)
)
)
SimpleXMLIterator クラス
導入
SimpleXMLIterator は、SimpleXMLElement オブジェクトのすべてのノードに対する再帰的な反復処理を提供します。
クラス概要
SimpleXMLIterator
SimpleXMLIterator
extends
SimpleXMLElement
implements
RecursiveIterator
,
Traversable
,
Iterator
,
Countable
{
/* メソッド */
}目次
- SimpleXMLIterator::current — 現在の SimpleXML エントリを返す
- SimpleXMLIterator::getChildren — 現在の要素の子要素を返す
- SimpleXMLIterator::hasChildren — 現在の要素が子要素を持つかどうかを調べる
- SimpleXMLIterator::key — 現在のキーを返す
- SimpleXMLIterator::next — 次の要素に移動する
- SimpleXMLIterator::rewind — 最初の要素に巻き戻す
- SimpleXMLIterator::valid — 現在の要素が有効かどうかを調べる
SimpleXMLIterator
ratfactor at gmail dot com
20-Jul-2009 09:08
20-Jul-2009 09:08
David Lanstein
18-Jan-2009 11:40
18-Jan-2009 11:40
Unlike the DirectoryIterator, for one, you'll need to call $it->rewind() before using the iterator in a for() or while() loop. Calling foreach() does rewind the iterator before iteration.
