簡體   English   中英

PHP DomXpath xpath 查詢子節點

[英]PHP DomXpath xpath query of Child Node

我正在嘗試使用 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 和 title 很好......但試圖查詢圖像是行不通的。 它實際上打破了。

任何幫助,將不勝感激。

你快到了。 您只需要在foreach循環中迭代$images即可。 所以更換

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()來提取一個 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