通过 class php DOMDocument 在其他元素中获取元素

Getting element inside other element by class php DOMDocument

大家好,我有这个Html代码:

<div class="post-thumbnail2">
   <a href="http://example.com" title="Title">
       <img src="http://linkimgexample/image.png" alt="Title"/>
   </a>
</div>

我想使用 php DOMDocument

获取 src 图像 (http://linkimgexample/image.png) and the value of the href link (http://example.com) 的值

我为了得到 link 所做的事情是这样的:

$divs = $dom->getElementsByTagName("div");

    foreach($divs as $div) { 
        $cl = $div->getAttribute("class");

        if ($cl == "post-thumbnail2") {
            $links = $div->getElementsByTagName("a");
            foreach ($links as $link)
                    echo $link->getAttribute("href")."<br/>";
        }
    }

我可以对 src img 做同样的事情

$imgs = $div->getElementsByTagName("img"); 
foreach ($imgs as $img)
    echo $img->getAttribute("src")."<br/>";

但有时网站上没有图片,Html 代码是这样的:

 <div class="post-thumbnail2">
   <a href="http://example.com" title="Title"></a>
</div>

所以我的问题是如何同时获得 2 值,这意味着当没有图像时我会显示一些消息

为了更清楚,这是一个例子:

<div class="post-thumbnail2">
       <a href="http://example1.com" title="Title">
           <img src="http://linkimgexample/image1.png" alt="Title"/>
       </a>
    </div>
<div class="post-thumbnail2">
       <a href="http://example2.com" title="Title"></a>
</div>
<div class="post-thumbnail2">
       <a href="http://example3.com" title="Title">
           <img src="http://linkimgexample/image2.png" alt="Title"/>
       </a>
</div>

我希望结果是

http://example1.com - http://linkimgexample/image1.png
http://example2.com - there is no image here !
http://example3.com - http://linkimgexample/image2.pn

DOMElement::getElementsByTagName returns a DOMNodeList,这意味着您可以通过检查 length 属性.

来确定是否找到了 img 元素
$imgs = $div->getElementsByTagName("img"); 
if($imgs->length > 0) {
    foreach ($imgs as $img)
        echo $img->getAttribute("src")."<br/>";
} else {
    echo "there is no image here!<br/>";
}

你应该考虑使用 XPath - 它让你穿越 DOM 的生活更容易一些:

$doc = new DOMDocument();
if($doc->loadHtml($xmlData)) {
    $xpath = new DOMXPath($doc); 
    $postThumbLinks = $xpath->query("//div[@class='post-thumbnail2']/a");

    foreach($postThumbLinks as $link) {
        $imgList = $xpath->query("./img", $link);

        $imageLink = "there is no image here!";

        if($imgList->length > 0) {
            $imageLink = $imgList->item(0)->getAttribute('src');
        }

        echo $link->getAttribute('href'), " - ", $link->getAttribute('title'),
             " - ", $imageLink, "<br/>", PHP_EOL;
    }
} else {
    echo "can't load HTML document!", PHP_EOL;
}