2017-06-13 67 views
0

我有這個DOMElement。如何從DOMElement獲取屬性

我有兩個問題:

1)什麼意思是指對象值被忽略?

2)如何從這個DOMElement獲取屬性?

object(DOMElement)#554 (18) { 
     ["tagName"]=> 
     string(5) "input" 
     ["schemaTypeInfo"]=> 
     NULL 
     ["nodeName"]=> 
     string(5) "input" 
     ["nodeValue"]=> 
     string(0) "" 
     ["nodeType"]=> 
     int(1) 
     ["parentNode"]=> 
     string(22) "(object value omitted)" 
     ["childNodes"]=> 
     string(22) "(object value omitted)" 
     ["firstChild"]=> 
     NULL 
     ["lastChild"]=> 
     NULL 
     ["previousSibling"]=> 
     string(22) "(object value omitted)" 
     ["nextSibling"]=> 
     string(22) "(object value omitted)" 
     ["attributes"]=> 
     string(22) "(object value omitted)" 
     ["ownerDocument"]=> 
     string(22) "(object value omitted)" 
     ["namespaceURI"]=> 
     NULL 
     ["prefix"]=> 
     string(0) "" 
     ["localName"]=> 
     string(5) "input" 
     ["baseURI"]=> 
     NULL 
     ["textContent"]=> 
     string(0) "" 
     } 

我已經讓這個類訪問該對象。這樣做的目的是爲了能夠從輸入字段獲取類型屬性。

<?php 

namespace App\Model; 

class Field 
{ 
    /** 
    * @var \DOMElement 
    */ 
    protected $node; 

    public function __construct($node){ 
     $this->node = $node; 
    } 

    public function getNode(){ 
     return $this->node; 
    } 

    public function getTagName(){ 

     foreach ($this->node as $value) { 
      return $value->tagName; 
     } 
    } 

    public function getAttribute(){ 


    } 
} 

回答

1
  1. 我相信(object value omitted)只是一些內部DOMvar_dump()限制,以防止傾倒關於對象圖太深和/或傾倒遞歸的信息。

  2. 然後,有關獲取有關屬性的信息:

    • 要獲得一個DOMElement的所有屬性,你可以使用attributes屬性,它是其父DOMNode類中定義,並返回一個DOMNamedNodeMapDOMAttr節點:

      // $this->node must be a DOMElement, otherwise $attributes will be NULL 
      $attributes = $this->node->attributes; 
      
      // then, to loop through all attributes: 
      foreach($attributes as $attribute) { 
          // do something with $attribute (which will be a DOMAttr instance) 
      } 
      // or, perhaps like so: 
      for($i = 0; $i < $attributes->length; $i++) { 
          $attribute = $attributes->item($i); 
          // do something with $attribute (which will be a DOMAttr instance) 
      } 
      
      // to get a single attribute from the map: 
      $typeAttribute = $attributes->getNamedItem('type'); 
      // (which will be a DOMAttr instance or NULL if it doesn't exist) 
      
    • 得到的只是一個屬性,名爲typeDOMElement,你可以使用:

      • DOMElement::getAttributeNode(),以獲取表示type屬性,像這樣一個DOMAttr節點:

        $typeAttr = $this->node->getAttributeNode('type'); 
        // (which will be NULL if it doesn't exist) 
        

      • DOMElement::getAttribute(),得到字符串值爲type,如下所示:

        $typeAttrValue = $this->node->getAttribute('type'); 
        // (which will an empty string if it doesn't exist)