0

我正在使用 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'字符串上的标签。你会得到错误

4

2 回答 2

1
...
} 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);
   ...
于 2013-04-26T03:58:45.647 回答
1

而不是使用$imageTags->hasAttributes()我通过使用解决了它$imageTags instanceof DOMNode

于 2013-04-26T04:03:13.677 回答