簡體   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