I need to get all parents of all page paragraphs and of all list items by PHP DOMDocument
Let's say, we have such html:
<div>
<p>Some text</p>
<p>Some text</p>
</div>
<section>
<p>Some text</p>
<p>Some text</p>
<p>Some text</p>
</section>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
If I use two following loops
$parents = [];
foreach($dom->getElementsByTagName('p') as $paragraph) {
$parents[] = $paragraph->parentNode;
}
foreach($dom->getElementsByTagName('li') as $li) {
$parents[] = $li->parentNode;
}
In the end I need just to add a class to each parent like
foreach($parents as $key => $parent) {
$parent->setAttribute('class', 'prefix_'.$key);
}
and would like to get the output
<div class="prefix_0">
...
</div>
<section class="prefix_1">
...
</section>
<div class="prefix_2">
...
</div>
But I get
<div class="prefix_0 prefix_1">
...
</div>
<section class="prefix_2 prefix_3 prefix_4">
...
</section>
<div class="prefix_5 prefix_6 prefix_7 prefix_8">
...
</div>
If I add the condition
if(!in_array($paragraph->parentNode, $parents)) {
it doesn't work as I see because we have not an array but node list
So how to avoid adding the same parent?
Very simply function to avoid it:
function compareParentNode($compare_node,$parents){
foreach($parents as $parent){
if ($parent->isSameNode($compare_node)) return true;
}
return false;
}
Using:
$parents = [];
foreach($dom->getElementsByTagName('p') as $paragraph) {
$parentNode = $paragraph->parentNode;
if (!compareParentNode($parentNode,$parents)){
$parents[] = $paragraph->parentNode;
}
}
See more isSameNode