2013-04-26 121 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