繁体   English   中英

PHP DOMDocument获取具有属性和值的任何元素

[英]PHP DOMDocument Get any element with attribute and the value

我正在尝试获取具有属性和值的元素。 我已经试过了:

public static function getElementByAttributeValue(\DOMDocument $domNode, $attribute, $value) {
    /** @var \DOMNode $node */
    foreach($domNode->childNodes as $node) {
        if($node->attributes && $node->attributes->length > 0) {
            $attrValue = self::getAttribute($attribute, $node->attributes);
            if($attrValue && strcmp($attrValue, $value) == 0) {
                return $node;
            }
        }
        if($node->hasChildNodes()) {
            return self::getElementByAttributeValue($node, $attribute, $value);
        }
    }
}

即使DOMDocument中存在该元素,它也会返回NULL。 我也尝试过这个:

    $xpath = new \DOMXPath($domNode);
    return $xpath->query("[@" . $attribute . "=\"" . $value . "\"]")->item(0);

xpath-> query返回false,但无法使-> item脱离false。

有什么解决办法吗?

嗯,第二个解决方案工作正常,但我需要这样做:

$xpath = new \DOMXPath($domNode);
return $xpath->query("//*[@" . $attribute . "=\"" . $value . "\"]")->item(0);

注意xpath表达式之前的//*

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM