Re: unexpected behaviour in SimpleXML (php 5.2.2)
| From: | Caroline Maynard | Date: | Thu, 24 May 2007 13:06:42 +0000 |
| Subject: | Re: unexpected behaviour in SimpleXML (php 5.2.2) | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-29717@lists.php.net to get a copy of this message | ||
Vesselin Kenashkov wrote:
Here is the first one - how one can find does a SimpleXMLElement has child nodes? Here is an example: -------- $str = '<rootnode><subnode></subnode></rootnode>'; $x = new SimpleXMLElement($str); if($x->subnode->children()) print 'yes'; elseThat's how SimpleXML is, but you can ease your pain by using count(): $x = new SimpleXMLElement($str); if (count($x->subnode->children()))print 'no';--------- will print 'no'; If the $str='<rootnode><subnode><newnode></newnode></subnode></rootnode>'; it will print yes. But the same will happen if the subnode has an attribute like: $str = '<rootnode><subnode id="2"></subnode></rootnode>'; But if we use foreach($x->subnode->children() as $key=>$value) in the latter example we will not get anything (which is correct). I think is wrong the children() method to return object when there are no child objects and the node has attributes. The workaround I use is to extend the SimpleXMLElement -------- class SimpleXMLElement2 extends SimpleXMLElement { public function has_children() { foreach($this->children() as $node)return true;return false; } } ------ And then we can check with if($x->subnode->has_children())
print 'yes';else
print 'no';