PHP domdocument if语句用于img标签没有alt属性或alt属性为空


PHP domdocument if statement for when img tag has no alt attribute or if alt attribute is empty?

我使用这段代码从使用domdocument的img标签获取alt属性。如果页面的图像没有alt属性,或者alt属性为空,则无法识别。我需要一些帮助来编写条件来检查空的alt属性以及根本没有。由于

$name =  trim($words->nodeName);
    if($name == 'img' ) 
        {
            $alt= $words->getAttribute('alt');
            if(!empty($alt)) 
        {
    $this->matchedAnchors[$this->count]['alt']     =  trim($words->getAttribute('alt'));

您可以使用XPath:

//img[normalize-space(@alt) != '']

的例子:

$xml = <<< XML
<ul>
    <li><img alt="foo"/></li>
    <li><img alt="   "/></li>
    <li><img alt=""/></li>
    <li><img /></li>
</ul>
XML;
$dom = new DOMDocument;
$dom->loadXML($xml);
$xp = new DOMXPath($dom);
foreach ($xp->query('//img[normalize-space(@alt) != ""]') as $img) {
    echo $dom->saveXML($img);
}

只打印

<img alt="foo"/>

codepad的演示