phpxpathdomxpathchild-nodes

PHP DomXpath xpath query of Child Node


I'm trying to use xpath to query some 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. It actually breaks.

Any help would be appreciated.


Solution

  • 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...

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