无法弄清楚如何确定SimpleXML节点是否为空

时间:2010-11-01 18:51:43

标签: php xml simplexml

所以我有这段代码:

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>");

     }

}

基本上,如果Passage节点存在,我正在尝试将ID保存到XML文件,但它似乎存储了每个ID,无论节点是否存在于Passage内。

2 个答案:

答案 0 :(得分:7)

如果您使用empty()

会发生什么
if( empty($PrintQuestion->content->multichoice->feedback->hint->Passage) ) {

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

}

答案 1 :(得分:4)

您可以将值转换为字符串并与空字符串进行比较(类似于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';
}