Unable to figure out how to determine if 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 am trying to save identifiers in an XML file if Passagenode exists , but it seems to save every identifier whether nodes exist in Passageor not.

+3
source share
2 answers

What happens if you use empty()

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

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

}
+7
source

You can specify the value as a string and compare with an empty string (sort of like checking the value of a simplexml object ):

$value = $root->child;

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

Source: https://habr.com/ru/post/1772537/


All Articles