Klávesové zkratky na tomto webu - rozšířené Na obsah stránky

porucha není na vašem přijímači

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?

Karma body: 16. Líbil se vám článek?

Tento článek byl uzavřen. Už není možné k němu přidávat komentáře ani hlasovat

Výtah na začátek článku na první komentář

Názory čtenářů v diskusích nejsou názory provozovatele webu, a ten za jejich obsah neodpovídá.

La Trine © 2004, 2008 David Grudl – o webu
provozuje Pachollini.

Jakékoliv užití obsahu, včetně převzetí článků nebo jejich částí, je bez předchozího písemného svolení autora zakázáno.

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