|
Posted by Janwillem Borleffs on 11/15/05 23:35
Sebastian Araya wrote:
> So far, so good. Now I want to set attributes and its values of the
> recent created node (playing with createAttribute() and
> setAttribute(), but I can't get the DOMElement from the new child
> DOMNode. Is it possible without issuing getElementsByTagName() or
> getElementById() ??
>
<?php
class Dom {
private $dom;
function __construct() {
$this->dom = new DomDocument;
}
function addElement($name, $value = '', $attrs = array()) {
$element = $this->dom->createElement($name, $value);
foreach ($attrs as $a => $v) {
$element->setAttribute($a, $v);
}
$this->dom->appendChild($element);
}
function saveXML() {
return $this->dom->saveXML();
}
}
$dom = new Dom;
$dom->addElement('root', 'test', array('foo' => 'bar'));
print htmlentities($dom->saveXML());
?>
> Is another easy way -using DomDocument object- to create a new
> element (such <table width="50%" border="0">...</table>) which has its
> attributes and its values ??
>
You could use the following (although not very pretty):
<?php
class Dom {
private $dom;
function __construct() {
$this->dom = new DomDocument;
}
function addElement($element) {
$dom = DomDocument::loadXML($element);
$node = $this->dom->importNode(
$dom->documentElement,
true
);
$this->dom->appendChild($node);
}
function saveXML() {
return $this->dom->saveXML();
}
}
$dom = new Dom;
$dom->addElement('<root foo="bar">test</root>');
print htmlentities($dom->saveXML());
?>
JW
[Back to original message]
|