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?
Asked
Active
Viewed 521 times
0

Ajay Mohite
- 119
- 3
- 13
-
you could use preg_match and get the first in the array. – Elliott Aug 03 '12 at 19:54
-
3@Elliott [The pony he comes...](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) – Niet the Dark Absol Aug 03 '12 at 19:56
-
@Kolink OMG that post is EPIC. I had never read it before. You just made my day! – Matt Aug 03 '12 at 19:58
1 Answers
0
Not easily. However, this should probably work:
- Get the
<h1>
as you have already - Get the next sibling. Check if is an image, or if not check if it has an image as a child/descendant
- Get the previous sibling. Same checks as above.
- 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.
- If you still have no image, take the parent node of the
<h1>
and repeat the entire process from Step 2. - 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.

Niet the Dark Absol
- 320,036
- 81
- 464
- 592