How can I get the nearest img tag to an h1 tag using PHP simple HTML DOM?

533 views Asked by At

I have code that gets the first h1 tag from a webpage. Now I want to get the first img tag that appears either before or after this h1 tag. How can I do this using PHP Simple HTML DOM?

1

There are 1 answers

0
Niet the Dark Absol On

Not easily. However, this should probably work:

  1. Get the <h1> as you have already
  2. Get the next sibling. Check if is an image, or if not check if it has an image as a child/descendant
  3. Get the previous sibling. Same checks as above.
  4. If you haven't found an image yet, get the next sibling ahead, and the previous behind, and repeat until you do or you run out of nodes.
  5. If you still have no image, take the parent node of the <h1> and repeat the entire process from Step 2.
  6. You should now have traversed the entire document, so if you have no result now then there's just no images anywhere.

Trim steps as needed.