使用PHP Simple Html Dom获取不同类型的上一个元素


Get previous element of a different type with PHP Simple Html Dom?

希望Simple Html Dom可以实现这一点,我正在抓取一个如下所示的页面:

<h5>this is title 1</h5>
<img>
<img>
<img>
<h5>this is title 2</h5>
<img>
<img>
<h5>this is title 3</h5>
<img>
<img>
<img>
<img>

等等。。。

我想让它看起来像:

<h5>this is title 1</h5>
<img>
<h5>this is title 1</h5>
<img>
<h5>this is title 1</h5>
<img>

<h5>this is title 2</h5>
<img>
<h5>this is title 2</h5>
<img>

这意味着,我认为,对于每个IMG,我都需要找到并获取之前的第一个H5。没有任何父div或任何结构可以让它变得更容易,这几乎就是我所描述的

我使用的代码看起来像这样(简化):

foreach($html->find('img') as $image){
//do stuff to the img
$title = $html->find('h5')->prev_sibling();

echo $title; echo $image;}

我使用prev_sbling所尝试的一切都会导致"致命错误:在非对象上调用成员函数prev_siling()",我想知道我尝试使用PHP Simple HTML Dom是否可行。我希望如此,我试过的所有其他刮胡器都让我把头发拔了出来。

是的,因为您没有将整个页面加载为dom,所以您实际上拥有的是DOMElement的列表,并且上一个子项将为NULL。

与之前的发现不同,你基本上可以做的是,有一个移动指针

$all = get all elements,
$title = null;
foreach ($all as $e) {
  if ($e == "h5") {
    $title = $e;
    continue;
  }
  echo $title . $e;
}

有一些sedo代码,但你会明白我的意思。

本质上,您希望选择所有h5元素以及所有img元素。然后,您循环浏览它们,并检查它们的类型。如果是h5元素,则更新$title变量,但不更新echo任何内容。如果是img,只需在图像之前回显$title即可。现在不需要去寻找h5,因为你已经缓存了它。

这里有一个例子:

foreach ( $html->find('h5, img') as $el )
{
    if ( $el->tag == 'h5' )
    {
        $title = $el->plaintext;
        continue;
    }
    echo "<h5>$title</h5>";
    echo $el->outertext;
}