php SimpleXML check if a child exists

Solution 1:

It might be better to wrap this in an isset()

if(isset($A->b->c)) { // c exists

That way if $A or $A->b don't exist... it doesn't blow up.

Solution 2:

SimpleXML always return Object. If there is no child, empty object is returned.

if( !empty($a->b)){
  var_dump($a->b);
}

Solution 3:

I solved it by using the children() function and doing a count() on it, ignoring an PHP error if there are no children by putting an @ before the count-call. This is stupid, but it works:

$identification = $xml->identification;
if (@count($identification->children()) == 0)
  $identification = $xml->Identification;

I hate this..

Solution 4:

After some experimentation, I've discovered that the only reliable method of checking if a node exists is using count($xml->someNode).

Here's a test case: https://gist.github.com/Thinkscape/6262156