You are here: Re: DomDocument: setting attributes to a new node « PHP Programming Language « IT news, forums, messages
Re: DomDocument: setting attributes to a new node

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

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация