ThinkingInBits
ThinkingInBits

Reputation: 11472

Can't figure out how to determine if a SimpleXML node is empty

So I have this code:

foreach ($xml->PrintQuestion as $PrintQuestion) {

     //if hint doesn't exist, store question id
     if (!$PrintQuestion->content->multichoice->feedback->hint->Passage) {

         fwrite($fp, "<contentid filename=\"$value\">" . $PrintQuestion->attributes()->id . "</contentid>");

     }

}

Basically, I'm trying to save IDs to an XML file if the Passage node exists, but it seems to be storing every ID whether nodes exist within Passage or not.

Upvotes: 3

Views: 3954

Answers (2)

bluestraggler
bluestraggler

Reputation: 91

You can cast the value as a string and compare to an empty string (sort of like how to check a value of simplexml object):

$value = $root->child;

if ((string)$value === '') {
  echo 'This passes if the child element existed, but was empty';
}

Upvotes: 4

Baylor Rae&#39;
Baylor Rae&#39;

Reputation: 4010

What happens if you use empty()

if( empty($PrintQuestion->content->multichoice->feedback->hint->Passage) ) {

    fwrite($fp, "<contentid filename=\"$value\">" . $PrintQuestion->attributes()->id . "</contentid>");      

}

Upvotes: 7

Related Questions