Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP DOMElement is Immutable. = 'No Modification Allowed Error'

Tags:

dom

php

xml

I cannot understand why this fails. Does a DOMElement need to be part of a Document?

$domEl = new DOMElement("Item"); 
$domEl->setAttribute('Something','bla'); 

Throws exception

> Uncaught exception 'DOMException' with message 'No Modification Allowed Error';

I would have thought I could just create a DOMElement and it would be mutable.

like image 852
Keyo Avatar asked Jun 15 '11 02:06

Keyo


2 Answers

From http://php.net/manual/en/domelement.construct.php

Creates a new DOMElement object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument::createElement or DOMDocument::createElementNS.

like image 82
Gordon Avatar answered Oct 15 '22 07:10

Gordon


I needed to pass one instance of \DOMElement to a function in order to add children elements, so I ended up with a code like this:

class FooBar
{
    public function buildXml() : string
    {
        $doc = new \DOMDocument();
        $doc->formatOutput = true;

        $parentElement = $doc->createElement('parentElement');
        $this->appendFields($parentElement);

        $doc->appendChild($parentElement);

        return $doc->saveXML();
    }

    protected function appendFields(\DOMElement $parentElement) : void
    {
        // This will throw "No Modification Allowed Error"
        // $el = new \DOMElement('childElement');
        // $el->appendChild(new \DOMCDATASection('someValue'));

        // but these will work
        $el = $parentElement->appendChild(new \DOMElement('childElement1'));
        $el->appendChild(new \DOMCdataSection('someValue1'));

        $el2 = $parentElement->appendChild(new \DOMElement('childElement2'));
        $el2->setAttribute('foo', 'bar');
        $el2->appendChild(new \DOMCdataSection('someValue2'));
    }
}
like image 33
Tobias Sette Avatar answered Oct 15 '22 06:10

Tobias Sette