创建具有多个属性的节点

时间:2017-05-24 09:08:50

标签: php dom xpath

我想创建一个节点脚本并使用多个属性设置它

这是我想要的:

.embed-responsive {
    position: relative;
    display: block;
    height: 0;
    padding: 0;
    overflow: hidden;
}
.embed-responsive .embed-responsive-item,
.embed-responsive iframe,
.embed-responsive embed,
.embed-responsive object,
.embed-responsive video {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border: 0;
}
.embed-responsive-16by9 {
    padding-bottom: 56.25%;
}
.embed-responsive-4by3 {
    padding-bottom: 75%;
}

问题是我只能定义一个属性。

1 个答案:

答案 0 :(得分:0)

你可以做的是扩展DOMElement(定义属性mutator方法的类),然后用DOMDocument注册它们。

如果你想要更加花哨一点,你也可以扩展DOMDocument,默认情况下合并这种行为,例如在你自己的命名空间中Dom;

<强>的Dom \元素

namespace Dom;

class Element
  extends \DOMElement
{
  // I think something like this would make
  // a little more sense than your original example
  // that would probably set all attributes to the same value
  public function setAttributes( array $attributes ) {
    foreach( $attributes as $name => $value ) {
      $this->setAttribute( $name, $value );
    }
  }
}

<强>的Dom \文献

namespace Dom;

class Document
  extends \DOMDocument
{
  public function __construct( $version = '1.0', $encoding = null ) {
    parent::__construct( $version, $encoding );

    // we register our custom DOMElement class
    // you can do this for all DOM classes
    // that are derivatives of DOMNode
    $this->registerNodeClass( 'DOMElement', 'Dom\Element' );
  }
}

使用示例:

$doc = new Dom\Document;
$scriptElement = $doc->createElement( 'script' );
$scriptElement->setAttributes( array(
  'defer' => '',
  'async' => '',
  'src'   => $instagram_js_path
) );