Я хочу создать скрипт узла и установить его с несколькими атрибутами
Это хочу я пытаюсь сделать:
$script_insta_node = $dom->createElement('script');
$script_insta_node->setAttribute('async defer src', $instagram_js_path);
Проблема в том, что я могу определить только один атрибут.
Что вы могли бы сделать, это продлить DOMElement
(класс, который определяет методы мутатора атрибута), а затем зарегистрируйте их DOMDocument
.
Если вы хотите получить немного больше фантазии, вы можете расширить DOMDocument
а также включить это поведение по умолчанию, например, в собственное пространство имен 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 );
}
}
}
Дом \ Document:
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
) );
Других решений пока нет …