Using DOMDocument, is it possible to get all elements that exists within a certain DOM?

孤者浪人 提交于 2019-12-12 07:43:39

问题


Let's say I have an HTML file with a lot of different elements, each having different attributes. Let's say I do not know beforehand how this HTML will look like.

Using PHP's DOMDocument, how can I iterate over ALL elements and modify them? All I see is getElementByTagName and getElementById etc. I want to iterate through all elements.

For instance. Let's say the HTML looks like this (just an example, in reality I do not know the structure):

$html = '<div class="potato"><span></span></div>';

I want to be able to some simple DOM modification (like in Javascript):

$dom = new DOMDocument();
$dom->loadHTML($html);

// Obviously the code below doesn't work but showcases what I want to achieve
foreach($dom->getAllElements as $element ){
    if(!$element->hasClass('potato')){
       $element->addClass('potato');
    } else{
       $element->removeClass('potato');
    }
}
$html = $dom->SaveHTML();

So in this instance, I would like the resulting html to look like this:

    $html = '<div><span class="potato"></span></div>';

So how can I iterate through all elements and do modifications on the fly in an foreach-loop? I really don't want to use regex for this.


回答1:


You can pass an asterisk * with getElementsByTagName() which returns all elements:

foreach($dom->getElementsByTagName('*') as $element ){

}

From the Manual:

name
The local name (without namespace) of the tag to match on. The special value * matches all tags.



来源:https://stackoverflow.com/questions/23269067/using-domdocument-is-it-possible-to-get-all-elements-that-exists-within-a-certa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!