PHP domdocument if当img标签没有alt属性或者alt属性为空时的语句?

时间:2011-10-16 16:03:37

标签: php domdocument

我正在使用此代码使用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'));

1 个答案:

答案 0 :(得分:2)

您可以使用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"/>

Demo on codepad

相关问题