2014-12-02 52 views
0

我對PHP的HTMLDOMDocument類比較陌生。如何使用php的HTMLDOMDocument類來刪除元素及其子元素

我在做這樣的事情:

$html = getHTML(); 

$htmlDOM = new DOMDocument('5.0', 'utf-8'); 
libxml_use_internal_errors(true); 
$htmlDOM->loadHTML(mb_convert_encoding(($html), 'HTML-ENTITIES', 'UTF-8')); 
libxml_clear_errors(); 

不幸的是所有被檢索的元素有類,而不是標識。通過標識或標籤檢索元素是非常簡單的...

但是,如何檢索一個特定的類內的幾個元素(例如:post-hover),然後從$htmlDOM刪除它們?

回答

1

不知道爲什麼他們還沒有添加getElementsByClassName呢。但是你可以使用XPath來查找,而不是(從here採取)的元素:

$finder = new DomXPath($dom); 
$classname = "my-class"; 
$nodes = $finder->query("//*[contains(@class, '$classname')]"); 

然後簡單地遍歷和刪除:

foreach($nodes as $node){ 
    $node->parentNode->removeChild($node); 
}