简体   繁体   English

PHP DomXpath xpath 查询子节点

[英]PHP DomXpath xpath query of Child Node

I'm trying to use xpath to query some HTML:我正在尝试使用 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>

This is the code I'm using:这是我正在使用的代码:

@ $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 />";
    }
  }

I'm gettin the href and title fine... but trying to query the image just isn't working.我得到了 href 和 title 很好......但试图查询图像是行不通的。 It actually breaks.它实际上打破了。

Any help would be appreciated.任何帮助,将不胜感激。

You are almost there.你快到了。 You just need to iterate over $images in a foreach loop.您只需要在foreach循环中迭代$images即可。 So replace所以更换

echo "<strong>Image: </strong>".$images->getAttribute('src'). "<br />";

with

foreach ($images as $image) {
     echo "<strong>Image: </strong>".$image->getAttribute('src'). "<br /and i>";
};

and it should work.它应该可以工作。

Assuming there is only 1 matching image, you can use XPaths evaluate() and string() in the XPath expression to extract the value in one go...假设只有 1 个匹配图像,您可以在 XPath 表达式中使用 XPaths evaluate()string()来提取一个 go 中的值...

$images = $xpath->evaluate("string(//img[contains(@class,'dx-smart-widget-report-cover_113_20')]/@src)", $element);
echo "<strong>Image: </strong>".$images. "<br />";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM