Hi,
I'm working with nested tags. I'd like to get the first level of tags only. How can I do?
For example...
$str = <<<HTML
<div>
no children 1
</div>
<div>
first parent
<div>
first child of first parent
<div class="foo bar">second child of first parent</div>
</div>
</div>
<div>
no children 2
</div>
<div>
second parent
<div>
first child of second parent
<div class="foo bar">second child of second parent</div>
</div>
</div>
HTML;
$html = str_get_html($str);
foreach ($html->find('div') as $onediv) {
echo $onediv . '<hr />';
}
Returns the list of all the divs...
no children 1
first parent
first child of first parent
second child of first parent
first child of first parent
second child of first parent
second child of first parent
no children 2
second parent
first child of second parent
second child of second parent
first child of second parent
second child of second parent
second child of second parent
... but I'd like to get only the parents (first level tags).
no children 1
first parent (with nested content)
no children 2
second parent (with nested content)
This is also for nested tables.
Do you have suggestions?
Thank you
Giorgio
Yes, this is pretty simple actually. The only requirement is that all elements must have a common ancestor. In your example, all divs are at the document root, which doesn't work. Put them inside a common element (body for example):
Now you can make use of the child combinator:
This will give you exactly what you want.
You can combine it with other combinators to get more specific elements. Here is a complete list of supported selectors: https://simplehtmldom.sourceforge.io/docs/1.8/api/simple_html_dom_node/find/#supported-selectors
Aha, that's great!
Thank you.
Gimmy
You are welcome.