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.
You can pass an asterisk
*
withgetElementsByTagName()
which returns all elements:From the Manual: