0

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?

4
  • What are you wanting to compare to to verify that the item doesn't exist? nodeValue? Commented Feb 22, 2019 at 21:41
  • Is your objective to get one div > p and one section > p in your parent array? Commented Feb 22, 2019 at 21:42
  • Can you update your question with sample output expected? ...and an example of what parents has it in already to compare to. Commented Feb 22, 2019 at 21:53
  • voodoo has the working solution for you. Commented Feb 22, 2019 at 22:05

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.