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

Viewed 11545

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.

2 Answers

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'));
    }
}
Related