如何从DOMElement获取属性

时间:2017-06-13 10:29:33

标签: php dom

我有这个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) ""
      }

我让这个类访问该对象。这样做的目的是我可以从输入字段中获取type属性。

<?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 个答案:

答案 0 :(得分: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)
      
    • 要从type获取一个名为DOMElement的属性,您可以使用:

      • DOMElement::getAttributeNode(),以获取代表DOMAttr属性的type节点,如下所示:

        $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)
        
相关问题