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

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

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.

Tags:

Php

Xml

Dom