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.
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
orDOMDocument::createElementNS
.
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'));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With