1 回答

TA贡献1854条经验 获得超8个赞
使用 xpath 遍历所有节点并使用两个 img 标签检索数据。
<?php $sample_html = '
<img src="http://www.whatever.com" alt="" />
abc
<br>
<h3>title</h3>
<div class="content">content <a href="link">my link</a></div>
<img src="http://goingnowhere.com" alt="">
def
<br>
<h3>title 2</h3>
<div class="content">content <a href="link">my link</a>
bla bla bla
</div>
';
$dom = new DOMDocument();
@$dom->loadHtml($sample_html);
$xpath = new DOMXPath($dom);
$snippet = '';
$arr = array();
$count = $xpath->query('//img')->length;
//loop through all img tags
for($i=0;$i<$count;$i++){
$node = $xpath->query('//img')->item($i);
$img_src = $node->getAttribute('src');//first image src
while ($node = $node->nextSibling) {
if (get_class($node) != 'DOMElement') {
continue;
}
if ($node->tagName == 'img') {
$snippet .= $dom->saveXML($node);
$arr[] = array(
'src'=>$img_src,
'content'=>$snippet
);
$img_src = $node->getAttribute('src');//last img src
$snippet = '';
break;
}
$snippet .= $dom->saveXML($node);
}
}
//fill last img data
$arr[] = array('src'=>$img_src,'content'=>$snippet);
- 1 回答
- 0 关注
- 210 浏览
添加回答
举报