I am using SimpleXMLIterator to parse some XML.
Doing a print_r shows that the SimpleXMLIterator Object created from the XML is like this:
{
[@attributes] => Array
(
[id] => abc
[type] => a
[timestamp] => 2001-12-12
)
[place] => US
[name] => Pete
[dob] => SimpleXMLIterator Object
(
[dd] => 03
[mm] => 05
[yyyy] => 1973
)
}
which also contains a dob SimpleXMLIterator Object – i.e. a child element of the XML tag.
I iterate over this object using the following code, which is recurive as i cant be sure how deep each XML tag goes:
function _prepareSimpleXMLIteratorObj(SimpleXMLIterator $xmlIterator) {
foreach ($xmlIterator as $key => $value){
// Count returns the number of children
if ($value->count() > 0) {
$this->_prepareSimpleXMLIteratorObj($value);
} else {
$this->assocArray[$key] = (string)$value;
}
}
}
assocArray is a member variable of the class.
This generates an assoc array from the Object.
Problem is when i use $value->hasChildren() instead of $value->count() i get false, even though $value->count() returns 3 for dob? Any ideas what i;m doing wrong?
Also if is do
if (($value instanceof SimpleXMLIterator))
i get false, even though dob is clearly a SimpleXMLIterator Object?
This method works but am just wondering about hasChildren and instanceof?
Here is the Sample XML
<tag id="abc" type="a" timestamp="2001-12-12">
<place>US</place>
<name>Pete</name>
<dob>
<dd>03</dd>
<mm>05</mm>
<yyyy>1973</yyyy>
</dob>
</tag>
Thanks
the hasChildren method is not working for you because it is not doing what you think. The key lies in this line in the documentation:
When it says “current” it means the actual SimpleXMLElement returned by the current() function as if you were iterating with foreach. Remember SimpleXMLIterator is designed to be an “iterator”
So, when your algorithm gets to the dob node and you call $value->hasChildren() its really checking if the item $value->current() has any children. So, in your example its checking whether the node /tag/dob/dd has any children, which it does not.