Undermine2k
Undermine2k

Reputation: 1491

php simple dom parser get parent of element

I am trying to retrieve the img SRC on some DIV's with no discerning class or parents: They simply exist on the page after <div class="content_end"></div>

I need to retrieve the image scr from these div's how can I only retrieve only these div's and not all other div's on the page:

I tried doing finding all images with div as the parent but that didnt work:

foreach($domParse->find('img') as $element) 
       echo $element->parent('div')->src;

I know in jquery there's a nextAll selector so i'm able to do something like:

$('.content_end').nextAll('div');

which returns to me the content I need: How can I do this in Simple Dom Parser:

HTML FORMAT

<div class="content_end"> </div>
-------------------------------------------------
<div style="postion:relative; height:90px;">
<img src="../">
</div>
<div style="postion:relative; height:90px;">
<img src="../">
</div>
---------------------------------------------

Upvotes: 1

Views: 2668

Answers (2)

user1978142
user1978142

Reputation: 7948

Since your'e targeting <img> tags which has a parent div with no class or id just use an attribute filter with the parent !class attribute filter. Consider this example:

include 'simple_html_dom.php';
$html_string = '
<div class="content_end"></div>
<div style="postion:relative; height:90px;">
    <img src="http://www.google.com/image1.jpg" />
</div>
<div style="postion:relative; height:90px;">
    <img src="http://www.stackoverflow.com/image2.png" />
</div>'; // your sample html structure
$domParse = str_get_html($html_string);

// div which has no class with img tag children
foreach($domParse->find('div[!class] img') as $img) {
    echo $img->src . '<br/>';
}

Should yield with as per example:

http://www.google.com/image1.jpg
http://www.stackoverflow.com/image2.png

Upvotes: 1

Johann Bauer
Johann Bauer

Reputation: 2606

I think what you're looking for is next_sibling():

foreach($domParse->find('div.content_end') as $element) 
   echo $element->next_sibling()->find("img")[0]->src;

Upvotes: 1

Related Questions