【问题标题】:php simple dom parser get parent of elementphp简单的dom解析器获取元素的父级
【发布时间】:2014-07-02 09:01:59
【问题描述】:

我正在尝试检索某些 DIV 上的 img SRC,但没有区分班级或父母:它们仅存在于 <div class="content_end"></div> 之后的页面上

我需要从这些div's 中检索图像scr 我怎样才能只检索页面上的这些 div 而不是所有其他 div:

我尝试查找所有以 div 作为父级的图像,但没有成功:

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

我知道在 jquery 中有一个 nextAll 选择器,所以我可以这样做:

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

返回给我我需要的内容:如何在 Simple Dom Parser 中执行此操作:

HTML 格式

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

【问题讨论】:

  • 也许你可以试试-&gt;find('div.content_end img')
  • @jreuab 图片不在 '
    好的,那么图像就在 div.content_end 之后的 div 中?
  • 因为你的目标是 img 标签,它的父 div 没有类或 id,所以只需使用带有父 !class 属性过滤器的属性过滤器

标签: php jquery html simple-html-dom


【解决方案1】:

我想你要找的是next_sibling():

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

【讨论】:

  • 不太工作得到:call to memeber function find() on a non-object 意思是 ->next_sibling() 没有返回任何内容。
【解决方案2】:

由于您的目标是 &lt;img&gt; 标签,其父 div 具有 no 类或 id,因此只需使用带有父 !class 属性过滤器的属性过滤器。考虑这个例子:

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/>';
}

应该按照示例屈服:

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

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签