gpt4 book ai didi

php - 创建具有多个属性的节点

转载 作者:行者123 更新时间:2023-12-03 02:56:10 25 4
gpt4 key购买 nike

我想创建一个节点脚本并为其设置多个属性

这就是我想做的事情:

$script_insta_node = $dom->createElement('script');
$script_insta_node->setAttribute('async defer src', $instagram_js_path);

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

最佳答案

你能做的就是扩展 DOMElement (定义属性修改器方法的类),然后将它们注册到 DOMDocument .

如果您想要更奇特一点,您也可以扩展 DOMDocument,默认情况下合并此行为,例如在您自己的命名空间 Dom 中;

Dom\Element:

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
) );

关于php - 创建具有多个属性的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44153879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com