2013-03-29 45 views
0

我要檢查所有的身體下方的標籤和檢查,排除是否有style屬性 我已經試過PHP DOMDocument hasAttribute與哪些元素相關聯?

$user_submitted_html = "This is Some Text"; 
$html = '<body>' . $user_submitted_html . '</body>'; 

$dom = new DOMDocument(); 
$dom->loadHTML($html_string); 
$elements = $dom->getElementsByTagName('body'); 
foreach($elements as $element) { 

    foreach($element->childNodes as $child) { 

     if($child->hasAttribute('style')) { 

      $child->removeAttribute('style') 

     }  
    } 
} 

它工作正常,如果$user_submitted_html不僅是文字,意思是,如果它有一些標籤在其但如果僅僅是文本,然後它給出了錯誤

Call to undefined method DOMText::hasAttribute() 

然後我得到的節點名稱,foreach循環

echo "Node Name: " . $child->nodeName 

它使

Node Name = #text 

什麼樣的節點名的就是這個,我已經echo'ed其他節點,它給,DIV,跨度等,我很熟悉。 我想知道哪些是元素hasAttribute不屬於他們,所以我可以把條件使用hasAttribute這樣

if($child->nodeName=="#text") { 
    continue; // skip to next iteration 
} 
if($child->hasAttribute('style')) { 
. 
. 
. 

或任何其他解決方案之前???

需要一個建議。如果我只從<div>,<span>,<p> and <a>中刪除樣式屬性。如果其餘的標籤可以使用style屬性,它會從xss安全嗎?

+0

這將有助於理解節點的一般概念只得到元素:http://stackoverflow.com/questions/4979836/noob-question - 關於-DOM文檔功能於PHP/4983721#4983721。比你更容易的方法是使用[XPath](http://schlitt.info/opensource/blog/0704_xpath.html)直接查詢具有style屬性的body元素的元素子元素,例如, '/ HTML /體/ * [@風格]' – Gordon

回答

1

我認爲不是檢查nodeName,而是檢查類$ child是一個實例。

if ($child instanceof DOMElement) 
{ 
    //do your stuff 
} 
0

您可以使用XPath與style屬性

$xpath = new DOMXPath($dom); 
$elements = $xpath->query('//[@style]'); 

foreach($elements as $e) { 
    $e->removeAttribute('style') 
}