PHP DOMNode::hasAttributes检查失败


PHP DOMNode::hasAttributes checks failure

我使用PHP DOMNode hasAttributes来检索所有元素的属性。到目前为止,一切都很顺利。我的代码如下。但是,这行else if($imageTags->hasAttributes() == false) is where I can't get it to work,它在我的页面上显示错误,而不是在代码失败时将用户重定向到索引php。我真正想要的是如果($imageTags->hasAttributes() == true)不等于TRUE。将用户重定向到index.php,而不显示错误。

function get_iframe_attr($string){
        $doc = new DOMDocument();
        $doc->loadHTML("$string");
            $imageTags = $doc->getElementsByTagName('iframe')->item(0);
            if ($imageTags->hasAttributes() == true) {
              foreach ($imageTags->attributes as $attr) {
                $name = $attr->nodeName;
                $value = $attr->nodeValue;
                $attr_val[] = "$name='"$value'" ";
              }
              echo  $implode_str = implode(" ", $attr_val);
            }else if($imageTags->hasAttributes() == false){
              header("Location: index.php");
            }
        } 

get_iframe_attr('<iframe src="" scrolling="no" width="600" height="438" marginheight="0" marginwidth="0" frameborder="0"></iframe>');

注意:如果您删除字符串上的'<iframe'标签。您将得到错误

...
} else if($imageTags->hasAttributes() == false){
   header("Location: index.php");
   die; // needed here to prevent code below, if any from executing
}
...

也在您的编辑笔记中删除iframe并获得错误,您需要检查$doc->getElementsByTagName('iframe')是否实际上抓取了任何东西,例如:

$imageTags = $doc->getElementsByTagName('iframe')
if ($imageTags->length > 0) {
   $imageTags = $imageTags->item(0);
   ...

我没有使用$imageTags->hasAttributes(),而是使用$imageTags instanceof DOMNode