Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 206
Weblurk Avatar asked Apr 24 '14 12:04

Weblurk


People also ask

How will you get all the matching tags in a HTML file in Dom?

If you want to find all HTML elements that match a specified CSS selector (id, class names, types, attributes, values of attributes, etc), use the querySelectorAll() method. This example returns a list of all <p> elements with class="intro" .

How can we find an element in Dom?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.


1 Answers

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.

like image 58
MrCode Avatar answered Sep 24 '22 14:09

MrCode