问题
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