如何解决子节点的 PHP DomXpath xpath 查询
我正在尝试使用 xpath 来查询一些 HTML:
<a target="_blank" class="dx-smart-widget-grid-item_113_20" href="https://link.com" title="Rules for the Road to One Source of Truth' with Jaguar Land Rover and Spark44">
<div class="dx-smart-widget-grid-info_113_20">
<img class="dx-smart-widget-report-cover_113_20" src="https://imagelink.com/preview.png" alt="The Alternative Text"/>
<div class="dx-smart-widget-grid-text_113_20">
<div class="dx-smart-widget-grid-title_113_20">The Alternative Text</div>
</div>
<span class="dx-smart-widget-report-assettype_113_20">On-Demand Webinar</span>
<img class="dx-smart-widget-partner-logo_113_20" src="https://logopath/logo.png" alt="censhare"/>
</div>
</a>
这是我正在使用的代码:
@ $dom->loadHTML($html);
$xpath = new DOMXpath($dom);
$elements = $xpath->query("//a[contains(@class,'dx-smart-widget-grid-item_113_20')]");
if (!is_null($elements)) {
foreach ($elements as $element) {
echo "<strong>Link: </strong>". $element->getAttribute('href'). "<br />";
echo "<strong>Title: </strong>". $element->getAttribute('title'). "<br />";
$images = $xpath->query("//img[contains(@class,'dx-smart-widget-report-cover_113_20')]",$element);
echo "<strong>Image: </strong>".$images->getAttribute('src'). "<br />";
}
}
我刚开始使用 href 和标题...但尝试查询图像是行不通的。它实际上坏了。
任何帮助将不胜感激。
解决方法
你快到了。您只需要在 $images
循环中迭代 foreach
。所以替换
echo "<strong>Image: </strong>".$images->getAttribute('src'). "<br />";
与
foreach ($images as $image) {
echo "<strong>Image: </strong>".$image->getAttribute('src'). "<br /and i>";
};
它应该可以工作。
,假设只有1张匹配的图片,可以在XPath表达式中使用XPaths evaluate()
和string()
一次性提取值...
$images = $xpath->evaluate("string(//img[contains(@class,'dx-smart-widget-report-cover_113_20')]/@src)",$element);
echo "<strong>Image: </strong>".$images. "<br />";
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。