php-解析具有img标签作为子元素的锚标签
作者:互联网
我需要找到所有具有img标签作为子元素的锚标签.考虑以下情况,
<a href="test1.php">
<img src="test1.jpg" alt="Test 1" />
</a>
<a href="test2.php">
<span>
<img src="test2.jpg" alt="Test 2" />
</span>
</a>
我的要求是生成带有src和alt的href属性列表
即
$output = array(
array(
'href' => 'test1.php',
'src' => 'test1.jpg',
'alt' => 'Test 1'
),
array(
'href' => 'test2.php',
'src' => 'test2.jpg',
'alt' => 'Test 2'
)
);
如何在PHP中匹配以上情况? (使用Dom Xpath或任何其他dom解析器)
提前致谢!
解决方法:
假设$doc是表示您的HTML文档的DOMDocument:
$output = array();
$xpath = new DOMXPath($doc);
# find each img inside a link
foreach ($xpath->query('//a[@href]//img') as $img) {
# find the link by going up til an <a> is found
# since we only found <img>s inside an <a>, this should always succeed
for ($link = $img; $link->tagName !== 'a'; $link = $link->parentNode);
$output[] = array(
'href' => $link->getAttribute('href'),
'src' => $img->getAttribute('src'),
'alt' => $img->getAttribute('alt'),
);
}
标签:domxpath,domparser,php 来源: https://codeday.me/bug/20191123/2065054.html