2016-12-11 32 views
0

属性と値を持つ要素を取得しようとしています。私はこれを試した:PHP DOMDocument属性と値を持つ要素を取得する

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->クエリはfalseを返し、それを得ることに失敗した - >アイテム偽のうち。

解決方法はありますか?

答えて

0

ああ第二の溶液が正常に動作しますが、私はこれを実行する必要があります。

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

お知らせ//* xpath式

関連する問題