2013-04-26 54 views
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,而不是显示错误。PHP DOMNode :: hasAttributes检查失败

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'标记。你会得到错误

+1

'如果你删除字符串上的' hek2mgl 2013-04-26 03:42:19

+0

我试图理解你的意思,“如果你删除字符串上的” 2013-04-26 03:45:10

+0

是的!这其实就是我想要做的。 – user2310422 2013-04-26 03:45:31

回答

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); 
    ... 
1

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