Na navigaci | Klávesové zkratky

DOMDocument::registerNodeClass is great

PHP 5.2.0 comes with a new DOM function named registerNodeClass(). What is it good for? The documentation says nothing as well as uncle Google. But this function is really great!

You know we can easily extends any of DOM classes. Take a look at this example:

class dgxElement extends DOMElement
{

	/**
	 * Converts to a SimpleXMLElement
	 */
	public function toSimple()
	{
		return simplexml_import_dom($this);
	}


	/**
	 * Removes this element from the document
	 */
	public function remove()
	{
		$this->parentNode->removeChild($this);
	}

	/**
	 * Kills all the children. But kindly!
	 */
	public function childless($node)
	{
		$this->nodeValue = '';
	}

}

We can instantize improved class dgxElement in our script. But there is a annoying limit. If we parse XML document from file or string, the document tree consists only of the standard objects DOMElement, DOMAttr, etc.

The solution is registerNodeClass. I hope an example will be better than my poor English: 🙂

$doc = new DOMDocument();

// and now use dgxElement instead of DOMElement!
$doc->registerNodeClass('DOMElement', 'dgxElement');

// parse a XML file
$doc->loadXML('<root><blog name="La Trine"/></root>');

// returns true
echo ($doc->documentElement instanceof dgxElement);

// method toSimple() test:
$simple = $doc->documentElement->toSimple();

foreach ($simple as $blog)
	echo $blog['name'];


// bye bye element <blog>
$doc->documentElement->firstChild->remove();

echo $doc->saveXML(); //  <root/>

Isn't it great?

You might be interested in


phpFashion © 2004, 2024 David Grudl | o blogu

Ukázky zdrojových kódů smíte používat s uvedením autora a URL tohoto webu bez dalších omezení.